Bits, Bytes and Integers

References

Outline

Everything is bits

Example: Counting in Binary

Encoding Byte Values

Encoding Byte Values

Hex Decimal Binary
0 0 0000
1 1 0001
2 2 0010
3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111

Encoding Byte Values

Hex Decimal Binary
8 8 1000
9 9 1001
A 10 1010
B 11 1011
C 12 1100
D 13 1101
E 14 1110
F 15 1111

Example Data Representations

C Data Typical 32-bit Typical-64 x86-64
char 1 1 1
short 2 2 2
int 4 4 4
long 4 8 8
float 4 4 4
double 8 8 8
pointer 4 8 8

Boolean Algebra

General Boolean Algebras

Example: Representing and Manipulating Sets

Example: Representing and Manipulating Sets

Bit-Level Operations in C

Contrast: Logical Operations in C

Shift Operations

Shift Examples

Encoding Integers

Example 3 Bit Integer Encodings

value unsigned two’s complement
000 (0+0+0) = 0 (0+0+0) = 0
001 (0+0+1) = 1 (0+0+1) = 1
010 (0+2+0) = 2 (0+2+0) = 2
011 (0+2+1) = 3 (0+2+1) = 3
100 (4+0+0) = 4 (-4+0+0) = -4
101 (4+0+1) = 5 (-4+0+1) = -3
110 (4+2+0) = 6 (-4+2+0) = -2
111 (4+2+1) = 7 (-4+2+1) = -1

Numeric Ranges

Example Numeric Ranges

Unsigned and Signed Numeric Values

Mapping Between Signed and Unsigned

Signed to Unsigned

Signed to Unsigned
Signed to Unsigned

Unsigned to Signed

Unsigned to Signed
Unsigned to Signed

Signed vs. Unsigned in C

Casting Surprises

Unsigned vs. Signed in C

Summary: Casting Rules

Sign Extension

Sign Extension Example

Truncation

Summary: Expanding and Truncating Rules

Unsigned Addition

\(UAdd\) Overflow

Visualizing Mathematical Integer Addition

Visualizing Unsigned Integer Addition

Two’s Complement Addition

\(TAdd\) Overflow

Visualizing Two’s Complement Addition

Integer Multiplication

Unsigned Multiplication in C

Signed Multiplication in C

Power-of-2 Multiply with Shift

Unsigned Power-of-2 Divide with Shift

Signed Power-of-2 Divide with Shift

Correct Signed Power-of-2 Divide with Shift

Negation: Complement and Increment

Arithmetic: Basic Rules

Byte-Oriented Memory Organization

Machine Words

Word-Oriented Memory Organization

Byte Ordering

Examining Data Representations

Representing Strings

Reading Byte-Reversed Listings

Summary