The Complete Guide to Bits, Bytes and Number Systems for Programmers
A complete guide to bits, bytes, binary, hex and octal for programmers, with conversions, binary arithmetic, masks, memory, ASCII and hex dumps worked in C.

Every program you will ever write runs on a machine that knows only two things: on and off. Everything else, numbers, text, images, machine code, is a convention for reading patterns of those two states. A programmer who understands the conventions can read a hex dump, decode a register, size a buffer, spot why a byte printed as ffffff80 and know why 0.1 is never quite 0.1. A programmer who does not will treat these as accidents. This guide builds the foundation in order: what a bit and a byte are, how positional number systems work in any base, how to convert between binary, octal, decimal and hex by hand and in C, how a computer adds and subtracts, how bitwise operators and masks work, how negative numbers, text and memory are laid out, and how to read the bytes of a file. Every section has code with its exact output, written for GCC 14 and the C17 standard on a little-endian 64-bit Linux machine, and every section points to a focused post that goes deeper. It is the first guide in the Fundamentals topic. The two that follow cover integers and floating point.
Why computers use bits
A circuit that tells two voltages apart is cheap, fast and reliable. One that must tell ten apart is expensive and fragile, because every extra level shrinks the margin between neighbours, and noise in a real wire is never zero. Early designers tried decimal machines and abandoned them. Binary hardware has a wide margin: anything below a threshold is a 0 and anything above is a 1, and a small amount of noise does not change the reading. Boolean logic, covered in the post on truth tables, maps exactly onto two values, so a handful of gate types, AND, OR, NOT and XOR, is enough to build addition, comparison, selection and memory.
A bit, short for binary digit, is one such value: 0 or 1. It is the smallest unit of information, the answer to one yes or no question. A single bit is too small to address, so memory is organised in groups. The standard group is the byte, eight bits, which on every mainstream platform is the smallest unit with its own address. Four bits are a nibble, which matters because one hexadecimal digit is exactly one nibble. A word is the natural width of a processor's registers, and its size depends on the machine, so documents that say word should say how many bits. The post on bits, nibbles, bytes and words lists the names that vendors use.
Positional notation in any base
You write numbers in a positional system without thinking about it. The decimal number 4,096 means 4 thousands, 0 hundreds, 9 tens and 6 ones: each digit is multiplied by a power of ten that depends on its position, and the products are added. The ten is the base, or radix, and the digits run from 0 up to one less than the base.
Any integer greater than 1 can be a base, and the rule is the same:
value = sum of (digit times base to the power of its position)
with positions counted from 0 at the right. In base 2 the digits are 0 and 1 and the place values are 1, 2, 4, 8, 16, 32, 64, 128. In base 8, octal, the digits are 0 to 7 and the places are 1, 8, 64, 512. In base 16, hexadecimal, there are sixteen digits, 0 to 9 and then A to F for ten to fifteen, and the places are 1, 16, 256, 4,096.
The same quantity can be written in each base. Take the value 200.
| Base | Name | Digits of 200 | How to read it |
|---|---|---|---|
| 2 | binary | 11001000 | 128 plus 64 plus 8 |
| 8 | octal | 310 | 3 times 64, plus 1 times 8, plus 0 |
| 10 | decimal | 200 | 2 times 100 |
| 16 | hexadecimal | C8 | 12 times 16, plus 8 |
The number is the same. Only the spelling differs, and the compiler stores one pattern of bits whichever spelling you wrote in your source. The post on binary numbers works through the place values slowly, and the posts on hexadecimal and octal cover those two bases.
Binary and the count of values
With n bits you can write 2 to the power n different patterns, because each bit doubles the count. Eight bits give 256 patterns, sixteen give 65,536 and thirty-two give 4,294,967,296. Read as unsigned numbers, the patterns represent 0 up to 2 to the n minus 1, so a byte holds 0 to 255. Read in other ways, the same patterns can mean negative numbers, characters or colours, and nothing in the bits themselves says which reading is intended. That is the single most important idea in this guide: bits have no meaning until a type or a format gives them one.
Two more facts follow from the doubling. A number written in binary with n digits is less than 2 to the n, so counting the digits tells you the size class of a value at a glance. And a pattern with a single 1 and zeros after it is a power of two: 1000 is 8, 10000 is 16. The post on powers of two collects the ones you will see constantly.
Why hex is the working notation
Binary is exact and unreadable at length. A 32-bit value is thirty-two digits, and nobody compares two of them by eye. Hexadecimal solves that because sixteen is a power of two: each hex digit is exactly four bits, so converting between binary and hex needs no arithmetic, only a lookup of sixteen patterns. The byte 10110100 is the nibbles 1011 and 0100, which are B and 4, so it is 0xB4. A 32-bit value is always eight hex digits and a 64-bit value sixteen, so the width is visible in the text.
| Bits | Hex | Bits | Hex |
|---|---|---|---|
| 0000 | 0 | 1000 | 8 |
| 0001 | 1 | 1001 | 9 |
| 0010 | 2 | 1010 | A |
| 0011 | 3 | 1011 | B |
| 0100 | 4 | 1100 | C |
| 0101 | 5 | 1101 | D |
| 0110 | 6 | 1110 | E |
| 0111 | 7 | 1111 | F |
Learn this table. Debuggers, datasheets, packet captures, memory maps and colour codes all use hex, and fluency with it removes most of the friction of low-level work. Octal does the same job with three bits per digit and survives in Unix permission modes such as 0755, where each digit is the read, write and execute bits of one class of user.
Converting between bases by hand
Four procedures cover every case. The post on converting by hand has worked tables for each, and this section gives the rules.
To decimal from any base: multiply each digit by its place value and add. The hex number 1F4 is 1 times 256, plus 15 times 16, plus 4, which is 500.
From decimal to any base: divide repeatedly by the base and read the remainders from last to first. To write 500 in hex, divide by 16 to get 31 remainder 4, divide 31 by 16 to get 1 remainder 15 (F), and divide 1 by 16 to get 0 remainder 1. The remainders from last to first are 1, F, 4.
Between binary and hex: group the bits in fours from the right, padding on the left, and replace each group with its digit. Reverse it to go back.
Between binary and octal: the same with groups of three.
You can have a program do the same job. The function below converts an unsigned value to a string in any base from 2 to 36, using the same repeated-division rule, and the program prints a few values in four bases and in base 36, which uses all the digits and letters.
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
static void to_base(uint64_t v, unsigned base, char *buf, size_t n)
{
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char tmp[65];
size_t i = 0;
if (v == 0) {
tmp[i++] = '0';
}
while (v > 0 && i < sizeof tmp - 1) {
tmp[i++] = digits[v % base];
v /= base;
}
size_t len = (i < n - 1) ? i : n - 1;
for (size_t k = 0; k < len; k++) {
buf[k] = tmp[i - 1 - k];
}
buf[len] = '\0';
}
int main(void)
{
const uint64_t values[] = { 45, 200, 255, 4096 };
char b2[65], b8[25], b10[25], b16[17], b36[14];
for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) {
to_base(values[i], 2, b2, sizeof b2);
to_base(values[i], 8, b8, sizeof b8);
to_base(values[i], 10, b10, sizeof b10);
to_base(values[i], 16, b16, sizeof b16);
to_base(values[i], 36, b36, sizeof b36);
printf("%4llu: bin=%s oct=%s dec=%s hex=%s b36=%s\n",
(unsigned long long)values[i], b2, b8, b10, b16, b36);
}
return 0;
}The digits are collected least significant first, because the remainder of the first division is the lowest digit, and then copied out in reverse. The i < sizeof tmp - 1 guard keeps the temporary buffer in bounds for the longest case, a 64-bit value in base 2, which needs 64 characters.
45: bin=101101 oct=55 dec=45 hex=2d b36=19
200: bin=11001000 oct=310 dec=200 hex=c8 b36=5k
255: bin=11111111 oct=377 dec=255 hex=ff b36=73
4096: bin=1000000000000 oct=10000 dec=4096 hex=1000 b36=35sCheck one line by hand. The row for 4096 shows that it is 2 to the 12, so binary is a 1 followed by twelve zeros, hex is 1000 because 16 cubed is 4,096, and octal is 10000 because 8 to the fourth is 4,096. The base-36 digits of 200 are 5 and k, and k stands for 20, so 5 times 36 plus 20 is 200.
Going the other way, the C library parses text in any base with strtoul and strtol. Base 0 means detect the base from the prefix: 0x for hex, a leading 0 for octal, otherwise decimal.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("strtoul(\"ff\", 16) = %lu\n", strtoul("ff", NULL, 16));
printf("strtoul(\"101101\", 2) = %lu\n", strtoul("101101", NULL, 2));
printf("strtoul(\"0xFF\", 0) = %lu\n", strtoul("0xFF", NULL, 0));
printf("strtoul(\"0377\", 0) = %lu\n", strtoul("0377", NULL, 0));
printf("strtoul(\"377\", 0) = %lu\n", strtoul("377", NULL, 0));
return 0;
}strtoul("ff", 16) = 255
strtoul("101101", 2) = 45
strtoul("0xFF", 0) = 255
strtoul("0377", 0) = 255
strtoul("377", 0) = 377The last two lines are the leading-zero rule that also governs C source literals: 0377 is octal and 377 is decimal. That is the reason a number padded with zeros for alignment in code can change value without any warning.
Printing numbers in other bases
printf has conversions for hex and octal, %x, %X and %o, with the flags # for a prefix and 0 with a width for padding. Until C23 there is no standard binary conversion, so a small helper prints bits. The post on printing numbers in binary, hex and octal covers both, and the hex dump program later in this guide uses them. The helper below is the one you will reuse throughout: it prints the low width bits of a value from the most significant down, and every later program in this guide relies on the same idea.
#include <stdint.h>
#include <stdio.h>
static void print_bits(uint32_t v, int width)
{
for (int i = width - 1; i >= 0; i--) {
putchar(((v >> i) & 1u) ? '1' : '0');
}
}
int main(void)
{
uint32_t v = 0xB4u;
printf("0x%02X = ", (unsigned)v);
print_bits(v, 8);
printf(" = %u = 0%o\n", (unsigned)v, (unsigned)v);
return 0;
}The shift moves the bit of interest into position 0 and the mask & 1u isolates it. Counting down from width - 1 prints the most significant bit first, so the text reads like a hand-written binary number.
0xB4 = 10110100 = 180 = 0264How a computer adds
Addition in binary works exactly like decimal addition by columns, with only two digits. Add the bits in a column plus any carry. If the total is 0 or 1, write it down. If it is 2, write 0 and carry 1, and if it is 3, write 1 and carry 1. The full-adder circuit that does this for one column has an elegant description in logic: the sum bit is the XOR of the two input bits and the carry-in, and the carry-out is 1 when at least two of the three inputs are 1. Chain eight of these, passing each carry to the next column, and you have an 8-bit adder, called a ripple-carry adder. The program below builds one from bit operations alone.
#include <stdint.h>
#include <stdio.h>
static uint8_t add8(uint8_t a, uint8_t b, unsigned cin, unsigned *cout)
{
uint8_t sum = 0;
unsigned carry = cin;
for (int i = 0; i < 8; i++) {
unsigned x = (a >> i) & 1u;
unsigned y = (b >> i) & 1u;
unsigned s = x ^ y ^ carry;
carry = (x & y) | (carry & (x ^ y));
sum |= (uint8_t)(s << i);
}
*cout = carry;
return sum;
}
int main(void)
{
unsigned c;
uint8_t r;
r = add8(45, 19, 0, &c);
printf("45 + 19 = %3u carry %u\n", r, c);
r = add8(200, 100, 0, &c);
printf("200 + 100 = %3u carry %u\n", r, c);
r = add8(255, 1, 0, &c);
printf("255 + 1 = %3u carry %u\n", r, c);
return 0;
}Each iteration handles one column, from the least significant. The expression carry & (x ^ y) is the carry that arrives and propagates, and x & y is the carry that the column generates by itself, and the two cases are ORed.
45 + 19 = 64 carry 0
200 + 100 = 44 carry 1
255 + 1 = 0 carry 1The second and third lines show overflow in its plainest form. The true sum of 200 and 100 is 300, which needs nine bits, and the adder returns the low eight, 44, and reports the ninth as a carry-out. A processor does the same and records the carry in a flag. Whether that is an error depends on how you read the bits, which brings us to negative numbers.
Negative numbers: two's complement
To represent negative integers, nearly every processor uses two's complement. In an n-bit value, the top bit has a weight of minus 2 to the n minus 1 instead of plus. For 8 bits, the weights are minus 128, 64, 32, 16, 8, 4, 2, 1, so 11111011 is minus 128 plus 64 plus 32 plus 16 plus 8 plus 2 plus 1, which is minus 5. The range is minus 128 to 127, one more negative value than positive. To negate a number, invert every bit and add 1.
The gain is that the adder above works unchanged for signed values. Adding 5 and minus 5 as unsigned patterns gives 00000101 plus 11111011, which is 256, so the byte is zero and the carry-out is 1, and the zero is the right answer for signed arithmetic. Subtraction follows: a - b is a + ~b + 1, invert and add one, which reuses the same circuit with the carry-in set to 1. The program reuses add8 for that.
#include <stdint.h>
#include <stdio.h>
static uint8_t add8(uint8_t a, uint8_t b, unsigned cin, unsigned *cout)
{
uint8_t sum = 0;
unsigned carry = cin;
for (int i = 0; i < 8; i++) {
unsigned x = (a >> i) & 1u;
unsigned y = (b >> i) & 1u;
sum |= (uint8_t)((x ^ y ^ carry) << i);
carry = (x & y) | (carry & (x ^ y));
}
*cout = carry;
return sum;
}
static uint8_t sub8(uint8_t a, uint8_t b, unsigned *cout)
{
return add8(a, (uint8_t)~b, 1, cout);
}
int main(void)
{
unsigned c;
uint8_t r = sub8(50, 8, &c);
printf("50 - 8 = %3u (as signed %4d) carry %u\n", r, (int)(int8_t)r, c);
r = sub8(8, 50, &c);
printf(" 8 - 50 = %3u (as signed %4d) carry %u\n", r, (int)(int8_t)r, c);
return 0;
}The result of 8 - 50 is 214 as an unsigned pattern, and minus 42 when read as a signed byte, which is the correct answer. The carry-out here means "no borrow", the inverse of what you might expect: a carry of 1 says the subtraction did not go below zero for unsigned values, and a carry of 0 says it did.
50 - 8 = 42 (as signed 42) carry 1
8 - 50 = 214 (as signed -42) carry 0The post on two's complement covers the representation fully, including the value that has no positive twin. The cast (int)(int8_t)r is how to read the same eight bits as signed: converting an out-of-range unsigned value to a signed type is implementation-defined in C17, and every mainstream compiler gives the two's complement reading.
Bitwise operators and masks
C exposes the bit-level operations directly. The six operators are & for AND, | for OR, ^ for XOR, ~ for NOT and the shifts << and >>. They act on each bit independently, and the post on bitwise operators has the full tables. Four idioms cover most uses.
Test a bit:
(v >> n) & 1u, or(v & mask) != 0.Set a bit:
v | mask.Clear a bit:
v & ~mask.Toggle a bit:
v ^ mask.
A mask is a constant with ones in the positions you care about. A set of independent options is conventionally packed into one integer, one bit per option, which is a flag word. The program below defines three permission flags, combines them and tests them.
#include <stdio.h>
enum perm {
PERM_READ = 1u << 0,
PERM_WRITE = 1u << 1,
PERM_EXEC = 1u << 2
};
static void show(unsigned p)
{
printf("%c%c%c (%u)\n",
(p & PERM_READ) ? 'r' : '-',
(p & PERM_WRITE) ? 'w' : '-',
(p & PERM_EXEC) ? 'x' : '-', p);
}
int main(void)
{
unsigned p = PERM_READ | PERM_EXEC;
show(p);
p |= PERM_WRITE;
show(p);
p &= ~PERM_EXEC;
show(p);
p ^= PERM_READ;
show(p);
return 0;
}The four statements walk through set, clear and toggle in turn. Starting from read and execute, setting write gives all three, clearing execute leaves read and write, and toggling read leaves only write.
r-x (5)
rwx (7)
rw- (6)
-w- (2)The values in brackets are the decimal readings of the flag words: read is 1, write is 2 and execute is 4, so r-x is 5, exactly the digit in chmod 755. The posts on setting and clearing bits and on bit masks and flag enums develop these idioms, including the traps of signed masks and shift counts.
Shifts and powers of two
A left shift by n multiplies by 2 to the n, until bits fall off the top, and a right shift divides by 2 to the n, rounding down for unsigned values. For signed negative values the right shift is arithmetic on every mainstream compiler, copying the sign bit, and the post on logical and arithmetic right shifts explains the difference. A shift by a count equal to or larger than the width of the type, or by a negative count, is undefined behaviour in C, so counts that come from outside need a guard.
Counting set bits is a classic exercise that uses shifts and masks, and a neat trick for it: x & (x - 1) clears the lowest set bit, so looping until x is zero counts the ones in as many steps as there are ones.
#include <stdint.h>
#include <stdio.h>
static unsigned count_bits(uint32_t x)
{
unsigned n = 0;
while (x != 0) {
x &= x - 1;
n++;
}
return n;
}
int main(void)
{
printf("count_bits(0) = %u\n", count_bits(0));
printf("count_bits(45) = %u\n", count_bits(45));
printf("count_bits(255) = %u\n", count_bits(255));
printf("count_bits(0x80000000) = %u\n", count_bits(0x80000000u));
return 0;
}For 45, binary 101101, the loop clears the bits one by one and counts four. The same trick tests for a power of two: a power of two has exactly one bit set, so x != 0 && (x & (x - 1)) == 0.
count_bits(0) = 0
count_bits(45) = 4
count_bits(255) = 8
count_bits(0x80000000) = 1Bytes in memory
Memory is a long array of bytes, each with an address. A value wider than one byte occupies several consecutive addresses, and the question of which byte comes first is byte order, or endianness. A big-endian machine stores the most significant byte at the lowest address, and a little-endian machine stores the least significant byte first. x86 and the Arm and RISC-V systems you are likely to meet run little-endian. Network protocols use big-endian, called network byte order, so data crossing a wire is converted with htons, htonl and their inverses.
The program below stores a 32-bit value and looks at its bytes through an unsigned char pointer, which the C aliasing rules allow for any object.
#include <stdint.h>
#include <stdio.h>
int main(void)
{
uint32_t v = 0x12345678u;
const unsigned char *p = (const unsigned char *)&v;
for (size_t i = 0; i < sizeof v; i++) {
printf("%02x ", p[i]);
}
putchar('\n');
return 0;
}On a little-endian machine the lowest address holds the least significant byte, 0x78, so the bytes come out in reverse of how the number is written.
78 56 34 12 This matters whenever you read a dump of a binary file or a network capture, a topic the rest of this series returns to in the posts on endianness. A multi-byte field in a dump is only readable once you know its order.
Sizes and units
The size of a type in bytes is sizeof, and the number of bits in a byte is CHAR_BIT, which POSIX fixes at 8. On the LP64 model used by 64-bit Linux and macOS, short is 2 bytes, int is 4, long is 8 and pointers are 8, while on 64-bit Windows long is 4. When a size must not change between platforms, use the exact-width types int32_t and uint64_t from stdint.h. The guide to integers in C covers this in depth.
Sizes of data are quoted in kilobytes and megabytes, and the prefixes have two meanings. The SI prefixes are powers of ten, so a kilobyte is 1,000 bytes. The IEC binary prefixes are powers of two: a kibibyte is 1,024 bytes, a mebibyte 1,048,576 and a gibibyte 1,073,741,824. A drive sold as one terabyte holds 10 to the power 12 bytes, and an operating system that reports sizes in gibibytes shows about 931 of them. The gap grows from 2.4 percent at kilo to nearly 10 percent at tera, and the post on kilobytes and kibibytes has the table. In your own code, write sizes in bytes or with the IEC names, and never leave "KB" ambiguous.
Characters are numbers
Text is bytes with an agreed table. The ASCII standard assigns codes 0 to 127 to the English letters, digits, punctuation and control characters. The capital A is 65, a is 97 and the digit 0 is 48, and the digits are consecutive, so c - '0' converts a digit character to its value. Lower-case and upper-case letters differ by exactly 32, which is a single bit, bit 5, so toggling the case of a letter is an XOR with 0x20.
#include <stdio.h>
int main(void)
{
const char *s = "Hi!";
for (const char *p = s; *p != '\0'; p++) {
printf("'%c' = %3d = 0x%02X\n", *p, *p, (unsigned)*p);
}
char word[] = "hello";
for (char *p = word; *p != '\0'; p++) {
*p = (char)(*p & ~0x20);
}
printf("%s\n", word);
printf("'7' - '0' = %d\n", '7' - '0');
return 0;
}The loop prints each character with its decimal and hex codes. Clearing bit 5 of a lower-case ASCII letter turns it into the upper-case one, which is safe only for the letters a to z, since the same operation on other characters corrupts them.
'H' = 72 = 0x48
'i' = 105 = 0x69
'!' = 33 = 0x21
HELLO
'7' - '0' = 7ASCII covers only 128 values. The Unicode standard assigns a number, a code point, to every character in every script, and UTF-8 is the common encoding of those code points as bytes: ASCII characters stay single bytes, and other characters take two to four bytes with the high bits marking continuation. A char is therefore a byte, not necessarily a character, and a string with accented letters has more bytes than characters. IBM mainframes use a different table, EBCDIC, which the posts on the Mainframe topic cover.
Reading the bytes of a file
When something is not text, the way to look at it is a hex dump: the offset of each row, the bytes in hex and the printable characters beside them. xxd and hexdump -C print one, and the post on reading a hex dump explains each column. Many file formats start with a magic number: PNG starts with 89 50 4e 47 0d 0a 1a 0a and an ELF executable with 7f 45 4c 46. Writing your own dump tool is a short exercise, and the post on writing a hex dump program in C builds it with fread. The core loop is as follows.
#include <ctype.h>
#include <stdio.h>
int main(void)
{
const unsigned char data[] = "Hello, bits!\n";
size_t n = sizeof data - 1;
printf("%08x ", 0u);
for (size_t i = 0; i < n; i++) {
printf("%02x ", data[i]);
}
printf(" |");
for (size_t i = 0; i < n; i++) {
putchar(isprint(data[i]) ? data[i] : '.');
}
puts("|");
return 0;
}The array literal is 14 bytes including the terminating null, which the program leaves out. Each byte prints as two hex digits, then the same bytes print as characters, with a dot for the newline, which has no visible form.
00000000 48 65 6c 6c 6f 2c 20 62 69 74 73 21 0a |Hello, bits!.|Registers, fields and bit numbering
Hardware exposes control through registers, and a register is a number whose bits each mean something: an enable flag in bit 0, a mode field in bits 4 to 6, a status field in the top byte. You read a field by shifting it down and masking, and write it by clearing the field and inserting the new value, the clear-then-insert pattern from the post on setting bits. Datasheets number the bits, and the numbering is not universal: most architectures call the least significant bit bit 0, while IBM POWER and z/Architecture manuals call the most significant bit bit 0. The post on bit numbering shows the conversion, lsb = width - 1 - msb, and a field extraction helper for each convention. Always read the numbering statement before using a position from a manual.
C also has a language feature for fields, the bit-field struct, but its layout is implementation-defined, so a struct is not a safe way to build a wire format. The post on packing and unpacking bit-fields shows the portable approach with shifts and masks.
Decimal digits in binary: BCD
Sometimes decimal digits must be preserved exactly, as in a real-time clock register or a mainframe money field. Binary-coded decimal stores each decimal digit in its own nibble, so 59 is the byte 0x59, which reads as decimal in a hex dump. It costs about 20 percent more space than binary, and arithmetic needs a correction of 6 when a digit sum passes 9. IBM's packed decimal adds a sign nibble. The post on BCD has the routines.
Packing data into bits
Because a byte or a word is just a container, programs routinely pack several small values into one. Three everyday examples show the technique, and each is a pattern you will meet in real code.
Colours
A 24-bit RGB colour has one byte each for red, green and blue, and web colours write it as six hex digits: #1E90FF is red 1E, green 90 and blue FF. Packing and unpacking is shifting and masking. Many small displays use a 16-bit format called RGB565, with 5 bits of red, 6 of green and 5 of blue, which throws away the low bits of each channel. Converting to it divides each channel, and converting back must refill the low bits, usually by copying the top bits downward so that full intensity maps to full intensity.
#include <stdint.h>
#include <stdio.h>
static uint32_t pack_rgb(unsigned r, unsigned g, unsigned b)
{
return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
}
static uint16_t to_565(unsigned r, unsigned g, unsigned b)
{
return (uint16_t)(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3));
}
int main(void)
{
uint32_t rgb = pack_rgb(30, 144, 255);
uint16_t c = to_565(30, 144, 255);
unsigned r5 = (c >> 11) & 0x1Fu;
unsigned g6 = (c >> 5) & 0x3Fu;
unsigned b5 = c & 0x1Fu;
printf("rgb888 = 0x%06X\n", (unsigned)rgb);
printf("rgb565 = 0x%04X\n", (unsigned)c);
printf("expanded: (%u, %u, %u)\n",
(r5 << 3) | (r5 >> 2), (g6 << 2) | (g6 >> 4), (b5 << 3) | (b5 >> 2));
return 0;
}The 565 value is 0x1C9F: red 30 shifts to 3, green 144 to 36, blue 255 to 31. Expanding back gives close values, not the originals, because the low bits were discarded: 30 comes back as 24 and 144 as 146, while 255 returns exactly to 255 because of the refill.
rgb888 = 0x1E90FF
rgb565 = 0x1C9F
expanded: (24, 146, 255)Network addresses
An IPv4 address is 32 bits, written as four decimal bytes. Packing the bytes into a uint32_t turns subnet arithmetic into bit operations: a network mask is a run of ones from the top, and the network address is the address ANDed with the mask.
#include <stdint.h>
#include <stdio.h>
int main(void)
{
unsigned a, b, c, d;
sscanf("192.168.1.10", "%u.%u.%u.%u", &a, &b, &c, &d);
uint32_t addr = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
uint32_t mask = 0xFFFFFF00u;
uint32_t net = addr & mask;
printf("address 0x%08X (%u)\n", (unsigned)addr, (unsigned)addr);
printf("mask 0x%08X\n", (unsigned)mask);
printf("network %u.%u.%u.%u\n", net >> 24, (net >> 16) & 0xFFu, (net >> 8) & 0xFFu, net & 0xFFu);
printf("host %u\n", (unsigned)(addr & ~mask));
return 0;
}The mask 0xFFFFFF00 is a /24 prefix: twenty-four ones and eight zeros. ANDing clears the host byte to get the network, and ANDing with the complement of the mask extracts the host part.
address 0xC0A8010A (3232235786)
mask 0xFFFFFF00
network 192.168.1.0
host 10Bit arrays
When you need many flags, such as one per item in a large set, an array of bits uses an eighth of the memory of an array of bytes. The index splits into a byte number, i >> 3, and a bit within the byte, i & 7. The sieve of Eratosthenes, which finds primes by crossing out multiples, is the standard demonstration.
#include <stdint.h>
#include <stdio.h>
#define N 50
static uint8_t bits[(N + 7) / 8];
static void set_bit(unsigned i) { bits[i >> 3] |= (uint8_t)(1u << (i & 7u)); }
static int test_bit(unsigned i) { return (bits[i >> 3] >> (i & 7u)) & 1; }
int main(void)
{
for (unsigned i = 2; i * i < N; i++) {
if (!test_bit(i)) {
for (unsigned j = i * i; j < N; j += i) {
set_bit(j);
}
}
}
for (unsigned i = 2; i < N; i++) {
if (!test_bit(i)) {
printf("%u ", i);
}
}
putchar('\n');
return 0;
}A set bit marks a composite number. The array is 7 bytes for 50 entries, and the shifts and masks are the same ones as in the flag examples, applied to an index.
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 Fractions in fixed point
Not every number in a program is an integer, and floating point is not the only way to store a fraction. A fixed-point number uses an integer and an agreed scale: in a format called Q8.8, a 16-bit value holds the number multiplied by 256, so the low byte is the fraction. The value 3.25 is stored as 832, which is 0x0340. Addition is ordinary integer addition. Multiplication produces a result scaled by 256 squared, so it is shifted right by 8 to restore the scale, after widening the operands so the product does not overflow.
#include <stdint.h>
#include <stdio.h>
typedef int16_t q8_8;
static q8_8 q_from(double x) { return (q8_8)(x * 256.0); }
static double q_to(q8_8 q) { return q / 256.0; }
static q8_8 q_mul(q8_8 a, q8_8 b)
{
return (q8_8)(((int32_t)a * (int32_t)b) >> 8);
}
int main(void)
{
q8_8 a = q_from(3.25);
q8_8 b = q_from(1.5);
printf("a = 0x%04X, b = 0x%04X\n", (unsigned)(uint16_t)a, (unsigned)(uint16_t)b);
printf("a * b = 0x%04X = %g\n", (unsigned)(uint16_t)q_mul(a, b), q_to(q_mul(a, b)));
return 0;
}The product is computed in 32 bits as 832 times 384, which is 319,488, and shifting right by 8 gives 1,248, or 0x04E0. Dividing by 256 recovers 4.875, which is 3.25 times 1.5.
a = 0x0340, b = 0x0180
a * b = 0x04E0 = 4.875Fixed point is common on microcontrollers without a floating-point unit and in signal processing, where the scale is chosen to fit the range of the data. It is also a good way to see that a fraction is only a convention: the hardware multiplies integers, and the position of the point exists in the programmer's head.
Checks and parity
One more use of bit operations is error detection. A parity bit records whether a group of bits has an odd or even number of ones, and it is the XOR of all the bits. A simple XOR checksum XORs all the bytes of a message together, and a receiver that XORs the data and the checksum gets zero when nothing flipped. These detect a single flipped bit, and they miss errors that cancel each other, which is why real protocols use CRCs, a stronger relative built from the same shifts and XORs.
#include <stdint.h>
#include <stdio.h>
static unsigned parity8(uint8_t v)
{
v ^= (uint8_t)(v >> 4);
v ^= (uint8_t)(v >> 2);
v ^= (uint8_t)(v >> 1);
return v & 1u;
}
static uint8_t xor_sum(const uint8_t *p, size_t n)
{
uint8_t x = 0;
for (size_t i = 0; i < n; i++) {
x ^= p[i];
}
return x;
}
int main(void)
{
const uint8_t msg[] = { 0x48, 0x69, 0x21 };
uint8_t sum = xor_sum(msg, sizeof msg);
printf("parity(0xB4) = %u\n", parity8(0xB4));
printf("parity(0x07) = %u\n", parity8(0x07));
printf("xor checksum = 0x%02X\n", (unsigned)sum);
return 0;
}The parity function folds the byte onto itself: after the three XORs, bit 0 holds the XOR of all eight bits. The byte 0xB4 has four ones, an even count, so its parity is 0, and 0x07 has three, so its parity is 1. The checksum of the three bytes of Hi! is 0x48 XOR 0x69, which is 0x21, XOR 0x21, which is 0.
parity(0xB4) = 0
parity(0x07) = 1
xor checksum = 0x00The zero result is a coincidence of the message, since 0x21 is the XOR of the first two bytes. It makes a neat reminder of how weak the checksum is: a message whose bytes XOR to zero is indistinguishable from an empty one.
Putting it together: reading a binary header
Everything so far meets in one task that systems programmers do constantly: take a block of bytes and pull the fields out of it. A PNG image file begins with an 8-byte signature and then a series of chunks. Each chunk is a 4-byte length, a 4-byte type and the data, and the first chunk is always IHDR, whose data starts with the image width and height as 32-bit numbers. The PNG specification says all multi-byte integers are big-endian, so a field is assembled from its bytes with shifts, in the order the file stores them, which makes the code independent of the byte order of the machine that runs it.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static uint32_t be32(const unsigned char *p)
{
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16)
| ((uint32_t)p[2] << 8) | (uint32_t)p[3];
}
int main(void)
{
const unsigned char png[] = {
0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A,
0x00, 0x00, 0x00, 0x0D,
'I', 'H', 'D', 'R',
0x00, 0x00, 0x03, 0x20,
0x00, 0x00, 0x02, 0x58
};
static const unsigned char sig[8] = { 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A };
if (memcmp(png, sig, sizeof sig) == 0) {
puts("signature ok");
}
printf("chunk length: %u\n", (unsigned)be32(png + 8));
printf("chunk type: %.4s\n", (const char *)(png + 12));
printf("width x height: %u x %u\n", (unsigned)be32(png + 16), (unsigned)be32(png + 20));
return 0;
}The helper be32 places the first byte in the top eight bits and the last in the bottom eight, which reads a big-endian field on any machine. Each byte is cast to uint32_t before it is shifted, because a unsigned char is promoted to a signed int and shifting 0x80 left by 24 would reach into the sign bit. The width bytes 00 00 03 20 assemble to 0x320, which is 800, and the height bytes 00 00 02 58 to 0x258, which is 600.
signature ok
chunk length: 13
chunk type: IHDR
width x height: 800 x 600Notice what the program does not do. It does not cast the byte array to a struct, which would depend on padding and byte order, and it does not read a uint32_t straight from the buffer, which would be a misaligned access on some processors and a byte-order bug on little-endian ones. The shifts and masks are the portable, explicit way, and they are the same operations this whole guide has covered: shift to position, mask to isolate, OR to combine.
Estimating and checking by sight
You will not always have a calculator, and a little mental arithmetic catches most mistakes before they reach a build. The key estimate is that 2 to the 10 is 1,024, which is close to a thousand, so 2 to the 20 is about a million, 2 to the 30 about a billion and 2 to the 40 about a trillion. A 32-bit value therefore tops out near four billion, and a 16-bit one near sixty-five thousand. When a program reports a count of 4,294,967,295 or 2,147,483,647, the digits are the signature of 2 to the 32 minus 1 and 2 to the 31 minus 1, and you can name the type that produced it.
Hex values have the same kind of shortcuts. A value whose hex digits are all F is the maximum of its width, 0x7F is the largest signed byte, 0x80 is the smallest, and any hex number ending in 0 is a multiple of 16, one ending in 00 a multiple of 256. An address ending in 000 is aligned to a 4 KiB page. When two values in a dump differ in a single digit, the difference is a power of 16 times that digit, which lets you tell a one-byte change from a bit flip at a glance.
Tools for checking your work
Several tools you already have will convert and verify numbers, and it is worth knowing them so you check answers independently of your own code. The shell's printf accepts the C conversions, bc converts bases when you set the output base, and a debugger prints any expression in several bases.
printf '%d %x %o\n' 255 255 255
echo 'obase=2; 45' | bc
printf '%d\n' 0x1F4255 ff 377
101101
500In GDB, p/x 255, p/o 255, p/t 255 and p/c 65 print hex, octal, binary and character forms of an expression, and x/8xb &var dumps eight bytes at an address. Using two independent methods, your own program and a tool, is the cheapest way to avoid a wrong answer: if they agree, a coincidental error is very unlikely.
Habits that keep bit code correct
Experienced programmers who work with bits share a short list of habits, and they all follow from what this guide has covered. First, use unsigned types for anything that is a pattern of bits and not a quantity, because the shifts and complements of signed values have undefined and implementation-defined corners. Second, give masks and field positions names, and define them once next to a comment that quotes the source of the numbers, such as the datasheet page. Third, use fixed-width types from stdint.h wherever a width is part of the meaning, and print them with the inttypes.h macros. Fourth, parenthesise every bitwise sub-expression inside a comparison, since the precedence rules are not what they look like. Fifth, test the edges: the value zero, the value with every bit set, the single set bit at each end, and a field that is full width. Most bit bugs show up there. Last, when a result looks odd, print it in hex and in binary before doing anything else, since the bits are the ground truth and every other view is an interpretation.
A field manual of common bugs
The same handful of mistakes account for most of the trouble beginners have with bits. Each of these has appeared earlier in this guide.
| Symptom | Cause | Fix |
|---|---|---|
a byte prints as ffffff80 | a signed char was sign-extended on the way to int | store bytes in unsigned char and cast before widening |
0x1F in a mask clears the wrong bits | the manual numbers bits from the left | convert with 31 - n and say so in a comment |
x & 1 == 0 always false | comparison binds tighter than & | write (x & 1) == 0 |
1 << 31 gives a warning or a wrong value | the literal 1 is a signed int | write 1u << 31 |
| a decimal constant changes value | a leading zero makes it octal | remove the zero, or write 0o in languages that have it |
| a shift by 32 does nothing, or crashes under UBSan | the count is not less than the width | guard the count before shifting |
~x compares unequal to the expected byte | ~ works on the promoted int | cast the result back to the narrow type |
| the sum of two bytes is wrong | the result needs nine bits | widen before adding, or keep the carry |
a uint32_t read from a file is backwards | byte order mismatch | read bytes and assemble with shifts |
| 1 TB shows as 931 GB | decimal and binary prefixes differ | compare in bytes, and write KiB and GiB |
Two compiler flags catch several of these: -Wall -Wextra warns about shifts, comparisons of different signedness and suspicious precedence, and -fsanitize=undefined reports an out-of-range shift or a signed overflow at run time. Build tests with both.
Exercises
Work these by hand first, then check with a program.
Convert
0xC3to binary and to decimal. The answer is11000011and 195.Write 1,000 in hex and in octal. The answer is
0x3E8and01750.What is
0x0F ^ 0xFF, and what does it do to the low nibble? The answer is0xF0: XOR with ones flips the bits, so the low nibble goes fromFto 0 and the high nibble from 0 toF.In 8-bit two's complement, what are
0xFF,0x80and0x7F? The answers are minus 1, minus 128 and 127.A device manual in MSB 0 numbering says a field is in bits 4 to 7 of a 16-bit register. Which bits is that in LSB 0 numbering? The answer is 11 down to 8, since
15 - 4is 11 and15 - 7is 8.How many bytes does a 24-bit colour image of 1,920 by 1,080 pixels need, with no compression? The answer is 1,920 times 1,080 times 3, which is 6,220,800 bytes, or about 5.93 MiB.
What comes next
This guide is the base of the Fundamentals ladder. The next rung is the guide to integers in C, which covers sizes, signedness, conversions and overflow, and then the guide to IEEE 754 floating point. After those, the topic continues into endianness and encodings, and then pointers and memory. Beginners who have worked through the examples here are ready for any of them.


