Bits and Representation Lab
Retrieval Prompts
- State from memory how many bits are in a byte and how one hex digit relates to bits.
- Write the rule for negating a two's-complement integer.
- Give the layout of an IEEE 754
float(sign, exponent, mantissa widths) from memory. - State whether signed overflow in C is defined or undefined behavior.
- Explain why
0.1 + 0.2 != 0.3in C.
Compare and Distinguish
Separate these pairs clearly:
- signed overflow versus unsigned wraparound in C
floatversusdoubleprecision and rangeNaNversusInf%xversus%Xversus%#xinprintf
Common Mistake Check
For each statement, identify the error:
- "
for (unsigned i = n; i >= 0; i--) ...eventually terminates." - "
int x = INT_MAX + 1;givesINT_MINon every C compiler." - "
float a = 0.1f + 0.1f + 0.1f; a == 0.3fis true because all values are small." - "
0xFF == -1on achar." - "Hex is a different number system from binary."
Mini Application
For each task, build with gcc -Wall -Wextra -O1 and note the output before running:
- Given
uint32_t x = 0x80000001;, printxas%uand as%d(after casting toint32_t). Explain the difference. - Write a function that takes a
uint32_tand prints it as 32 bits, MSB first, grouped in nibbles. - Given a
float f = 3.14f;, usememcpyto read the bit pattern into auint32_tand print it in hex. - Compute
(1 << 31)as bothintandunsigned, with-fsanitize=undefined; explain why one traps and the other does not. - For
int a = -5; int b = 3; printf("%d\n", a % b);, predict the sign of the result. Verify against the C standard (%follows truncation toward zero).
Lab Tasks
- Build a hex-dump utility: read a file or stdin and print 16 bytes per line with ASCII on the right. Compare output with
xxd. - Encode and decode an IEEE 754
floatby hand on paper, then verify with a program. Use the values1.0,-0.5,0.15625,0.1. - Write a loop that increments
int8_t x = 120; x += 10;five times and prints the result; annotate exactly where wraparound occurs and what the C standard says about it (note:int8_tis signed, so this is undefined behavior;uint8_tis defined).
Evidence Check
This page is complete only if, for any hex pattern up to 32 bits, you can:
- read it as unsigned, signed (two's complement), and IEEE 754
float - explain whether an arithmetic operation on it is defined behavior in C
- predict the sanitizer output before running the program