Bits#

Ben Reed

Thu, 2 Feb 2023

Integers#

  • Integers are stored as a binary numbers.

  • Each binary digit is referred to as a bit. Since binary numbers are base-2, each bit can be a 0 or 1.

  • Since modern processors manage memory in terms of 8-bit bytes, integers are generally stored as 8-bit, 16-bit, 32-bit, 64-bit, and sometimes 128-bit numbers.

  • Some languages or libraries provide access to larger numbers, sometimes even arbitrarily large numbers.

  • Signed integers use one of the bits for the sign, which means that an 8-bit unsigned integer can represent numbers from 0 to 28-1, but an 8-bit signed integer goes from -27 to 27-1.

Integer Representation#

All of these assignments will result in the unsigned 16-bit integer i storing the number 0000000100000001

i = 257
assert i == 0b100000001
i = 0x101
assert i == 0b100000001
i = 0b100000001
assert i == 0b100000001
i = 0o401
assert i == 0b100000001

Representing a number in a different base does not change how it is stored.

Bitmasking#

Since each bit is 0 or 1 we can do the equivalent of a logical operation as a bit operation where we treat 0 as false and 1 as true.

assert (True and True)  == True
assert (1 & 1)          == True
assert (True and False) == False
assert (1 & 0)          == False

We can do it to all the bits at once.

assert 0b11001101 & 0b1111 == 0b1101

Since all integers are binary numbers, the above can be expressed as:

assert 0b11001101 & 0xf == 13