zettelkasten

Search IconIcon to open search
Dark ModeDark Mode

Data Representation as Bits

#lecture note based on 15-213 Introduction to Computer Systems

H2 Bits

Either 0 or 1? That’s abstraction of electronic implementation. Votage isn’t discrete.

Representations - Bits are just bits, but we can represent int, long, float

Boolean Algebra -> In 2’s complement, flip bits and plus one flips sign

H2 Integers

Addition for signed and unsigned done the same way on hardware. Only interpreted differently.

Typical size (in byte) for C data types

type32-bit “ILP32”64-bit “LP64” / x86-64
char11
shoart22
int44
long48
float44
double88
pointer48

H2 Booleuan and Logical Operators

  • 0 is false, everything else is true.
  • All operators return 0 or 1
  • Has early termination
    • 0x69 || 0x55 => 0x01
    • p && *p possible, but not recommended

H2 Bit shifting

  • << always add 0 to right
  • >>
    • unsigned - logical - add 0 to left
    • 2’s complement - arithmatic - extend left-most bit
  • Shift $< 0$ or $\geq \text{size}$ are undefined behaviour

H2 Casting

  • Between signed and unsigned: maintain bit pattern and reinterpret
  • From shorter to longer signed: make enough copies of sign bit (i.e. left most bit)
  • From shorter to longer unsigned: add 0s to left
  • From longer to shorter signed/unsigned: truncate top bits

H2 Facts

  • -x == ~x + 1
  • constant integer like 42 defaults to signed. to get unsigned do 42U
  • if signed and unsigned in same expression, signed implicitely cast to unsigned
  • !!x != x, ~~x == x
  • x << k = $2^k x$, both signed and unsigned
  • When doing comparison ops on mix of signed and unsigned, things implicitely cast to unsigned

H2 Arithmatics

  • Addition - carry bit stored somewhere on hardware but discarded
  • Multiplication - sometimes we need $2w$ bits for muitiplying $w$ bits integers. The extra bits are discarded