Lab: a little data representation, part 2
Here's a list of questions. For each question, show how to answer the question by writing a little C code.
1. Integers
- Grab a copy of integers.c and save it in your mantis working directory.
- Read it, predict what it will do, and run it:
gcc -Wall -Werror -o integers integers.c ./integers > output.dat
- Look at the output.dat file's contents using hexdump. How does what the C program did correspond to what you see in the output file?
- (By the way, what did the ">" sign do in the command above?)
- In integers.c, change "j = 25" to "j = -25", save, recompile, rerun, and hexdump. What changed? Why did it change exactly like that?
2. A handy tool
If you want to know the exact bits contained in an int, do this:
int j = whatever;
printf("0x%08X\n", j);
It gets slightly weirder for long (note the l before the X)
long k = whatever;
printf("0x%016lX\n", k);
It gets even weirder for char. See below.
2. Some questions
- How many bytes are in an int? (don't forget the C sizeof function) (it's not really a function, but it looks like one, so whatever)
- How many bytes are in a long?
- How many bytes are in a char?
- How many bytes are in an unsigned int?
- How many bytes are in an unsigned long?
- How many bytes are in an unsigned char?
- If you do this:
int j = -1; unsigned int k = -1;what bits are in j? what bits are in k?
- What the heck is going on here?
char c1 = 0x41; printf("c1 as char: %c\n", c1); printf("c1 as decimal int: %d\n", c1); printf("c1 as hexadecimal int: %X\n", c1); char c2 = 0xCE; printf("c2 as char: %c\n", c2); printf("c2 as decimal int: %d\n", c2); printf("c2 as hexadecimal int: %X\n", c2);
- What the heck is going on here?
int j = -1; int k = (j >> 4); printf("j (-1): 0x%08X\n", j); printf("j >> 4: 0x%08X\n", k);
- Do the same thing as the previous item, but with j and k unsigned.