/* show_bytes.c Based on Sec. 2.1 in Bryant and O'Hallaron Modified by Tanya Amert for Fall 2023 Exploring the byte ordering of different types. Try changing the input in main to other values! Compile as usual: gcc -Wall -Werror -g -o show_bytes show_bytes.c Run with no command-line arguments: ./show_bytes */ #include #include // #define the printf %d display width to avoid magic numbers // reference: https://stackoverflow.com/questions/7105890/set-variable-text-column-width-in-printf #define DISPLAY_WIDTH 18 // Define a useful type to improve readability. typedef unsigned char * byte_ptr; // We'll view the byte orderings of many different types. void show_int(int i); void show_float(float f); void show_pointer(void *p); void show_string(const char *s); // We can also display a given value interpreted as // each of several types. void test_show_bytes(int val); // Explore byte orderings by changing the inputs to // test_show_bytes and show_string! int main() { // Print the bytes for a given bit sequence, interpreted // in several different ways test_show_bytes(0x2718); // Print the bytes for different "strings" printf("\n"); show_string("314159"); show_string("hello"); return 0; } /////////////////////////////////////////////////////////// // Other functions (e.g., show_int) will call this after // casting the value to a char array (i.e., byte_ptr). void show_bytes(byte_ptr start, size_t len) { int i; for (i = 0; i < len; i++) { printf(" %.2x", start[i]); } printf("\n"); } /////////////////////////////////////////////////////////// // Show the bytes of the given int. void show_int(int i) { printf("Int (%*d): ", DISPLAY_WIDTH, i); // see StackOverflow (above) on the * in %*d show_bytes((byte_ptr) &i, sizeof(int)); } // Show the bytes of the given float. void show_float(float f) { printf("Float (%*f): ", DISPLAY_WIDTH, f); show_bytes((byte_ptr) &f, sizeof(float)); } // Show the bytes of the given pointer (e.g., an address). void show_pointer(void *p) { printf("Pointer (%p): ", p); show_bytes((byte_ptr) &p, sizeof(void *)); } // Show the bytes of the given string. void show_string(const char *s) { // Add the appropriate number of spaces to line everything up printf("String"); for (int i = 0; i < DISPLAY_WIDTH - strlen(s); i++) printf(" "); // Now print the actual string in s printf("(\"%s\"): ", s); show_bytes((byte_ptr) s, strlen(s)); } // Show the given int interpreted as each of several types. void test_show_bytes(int val) { int ival = val; float fval = (float) val; int *pval = &ival; show_int(ival); show_float(fval); show_pointer(pval); }