Skip to main content

Bits and Representation Lab

Retrieval Prompts

  1. State from memory how many bits are in a byte and how one hex digit relates to bits.
  2. Write the rule for negating a two's-complement integer.
  3. Give the layout of an IEEE 754 float (sign, exponent, mantissa widths) from memory.
  4. State whether signed overflow in C is defined or undefined behavior.
  5. Explain why 0.1 + 0.2 != 0.3 in C.

Compare and Distinguish

Separate these pairs clearly:

  • signed overflow versus unsigned wraparound in C
  • float versus double precision and range
  • NaN versus Inf
  • %x versus %X versus %#x in printf

Common Mistake Check

For each statement, identify the error:

  1. "for (unsigned i = n; i >= 0; i--) ... eventually terminates."
  2. "int x = INT_MAX + 1; gives INT_MIN on every C compiler."
  3. "float a = 0.1f + 0.1f + 0.1f; a == 0.3f is true because all values are small."
  4. "0xFF == -1 on a char."
  5. "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:

  1. Given uint32_t x = 0x80000001;, print x as %u and as %d (after casting to int32_t). Explain the difference.
  2. Write a function that takes a uint32_t and prints it as 32 bits, MSB first, grouped in nibbles.
  3. Given a float f = 3.14f;, use memcpy to read the bit pattern into a uint32_t and print it in hex.
  4. Compute (1 << 31) as both int and unsigned, with -fsanitize=undefined; explain why one traps and the other does not.
  5. 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 float by hand on paper, then verify with a program. Use the values 1.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_t is signed, so this is undefined behavior; uint8_t is 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