"10239472" is 8 bytes, but 10239472 is
just 4[%inc bird.txt %]
0b prefix[%inc binary_notation.py %] [%inc binary_notation.out %]
[%inc hex_notation.py %] [%inc hex_notation.out %]
0100 is 41100 is -4[% table slug=“binary-3bit” tbl=“3bit.tbl” caption=“3-bit integer values using two’s complement.” %]
Can still determine sign by looking at the first bit
But two’s complement is asymmetric
No positive number to match the largest negative number
Operate on corresponding bits in representation
& (and) is 1 if both bits are 1, 0 otherwise
0b1100 & 0b1010 == 0b1000
12 & 10 == 8
| (or) is 1 if either bit is 1, 0
otherwise
0b1100 | 0b1010 == 0b1110
12 | 10 == 14
[% table slug=“binary-ops” tbl=“bitwise.tbl” caption=“Bitwise operations.” %]
Take a closer look at ~6
We are using two’s complement, so 6 is
0b000…00110
Its bitwise negation is 0b111…11001, which is
-7
Shifting up and down is almost like multiplying or dividing by 2
But what if the top bit changes?
0b1111 >> 1 is
0b0111, so -1/2 is 7[% figure slug=“binary-boxing” img=“boxing.svg” alt=“Boxed values” caption=“Using boxed values to store metadata.” %]
[% figure slug=“binary-arrays” img=“arrays.svg” alt=“Boxed arrays” caption=“Low-level and high-level array storage.” %]
struct Module[%inc pack_unpack.py %] [%inc pack_unpack.out %]
Not all bytes correspond to common characters
So Python uses two-digit hex representation
\xPQ
\x00 is a [%g null_byte “null byte” %] (value
0)
Easy to miss the actual A between one
\x00 and the next
[%inc pack_count.py %] [%inc pack_count.out %]
[%inc dynamic_format.py %] [%inc dynamic_format.out %]
Pack strings as a fixed-size count and that many bytes
Use bytes to convert character string to
bytes
[%inc variable_packing.py mark=pack %]
[%inc variable_packing.py mark=main %] [%inc variable_packing.out %]
[%inc variable_unpacking.py mark=main %] [%inc variable_unpacking.out %]
0b11101101:
1101 is the first four bits of the
character10
[%inc pack_unicode.py mark=main %] [%inc pack_unicode.out %]
open(filename, "r") converts bytes to characters
\r\n to Unix
\nopen(filename, "rb") to read in [%g binary_mode
“binary mode” %][% figure slug=“binary-concept-map” img=“concept_map.svg” alt=“Concept map for binary data” caption=“Concept map.” %]