Lesson 01
Bits, Booleans and Bitwise Operations
Goal
By the end of this lesson you will be able to:
-
Convert a decimal number to binary and back.
-
Read a number as bits, nibbles and bytes.
-
Name the width of a Rust integer type from the type itself.
-
Use the logical operators, which work on a whole value as true or false:
-
&&— AND -
||— OR -
!— NOT
-
Apply De Morgan’s laws when a NOT is involved.
-
Use the bitwise operators, which work on one bit at a time:
-
&— bitwise AND -
|— bitwise OR -
^— bitwise XOR -
!— bitwise NOT -
<<and>>— left and right shift
- Explain how a negative number is stored in memory.
The Shape of a Rust Program
Every Rust program starts in a function called main. The program runs the lines between its two braces, from the top down. This is the whole skeleton:
fn main() {
}
Every short example in this lesson goes between those two braces. let makes a variable, and println! prints one line:
fn main() {
let a: u8 = 5;
println!("{a}");
}
5
The name inside the braces of println! is the variable to print. Two slashes start a comment: everything after them on that line is a note for the reader, and the compiler ignores it.
Binary Basics
You count in decimal: ten digits, 0–9. A computer counts in binary: two digits, 0 and 1. That is the only difference.
Decimal to Binary
Divide by 2 over and over, writing down the remainder each time. Set it out as the short-division ladder you already use: the divisor on the left, the running result underneath, the remainder off to the right. Converting 13:
Stop when the result reaches 0, then collect the remainder column bottom to top — the direction of the arrow — to get the boxed answer.
The table below is the binary form of the numbers you meet most, each written as four bits. They come up constantly, so it is worth remembering them directly rather than running the ladder every time:
| Decimal | Binary | Decimal | Binary |
|---|---|---|---|
| 0 | 0000 | 8 | 1000 |
| 1 | 0001 | 9 | 1001 |
| 2 | 0010 | 10 | 1010 |
| 3 | 0011 | 11 | 1011 |
| 4 | 0100 | 12 | 1100 |
| 5 | 0101 | 13 | 1101 |
| 6 | 0110 | 14 | 1110 |
| 7 | 0111 | 15 | 1111 |
Binary to Decimal
Each position in binary holds a 0 or a 1, and each position is worth , starting from the right at . The value of the whole number is the sum of the positions that hold a 1. The positions holding a 0 add nothing.
Example:
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | |
|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | |
| 128 | 251 |
More examples:
00001101 | |
1010 | |
10011100 |
Bits, Nibbles and Bytes
| Unit | What it is |
|---|---|
| bit | One binary digit: 0 or 1 |
| nibble | 4 bits — 16 possible values (0–15) |
| byte | 8 bits — 256 possible values (0–255) |
A byte is the smallest piece of memory a computer normally works with. Memory is a long row of numbered slots, and each slot holds one byte, not one bit. Every larger amount of memory is therefore counted in bytes, and each step up multiplies by 1024:
| 1 kilobyte (KB) | = 1024 bytes |
| 1 megabyte (MB) | = 1024 KB |
| 1 gigabyte (GB) | = 1024 MB |
| 1 terabyte (TB) | = 1024 GB |
Why 1024 and Not 1000
Memory is binary, so its sizes fall naturally on powers of 2. is the power of 2 closest to 1000.
Widths of the Rust Integer Types
In Rust the name of an integer type tells you its width. There is no guessing and no “it depends on the machine”.
-
The letter is the sign.
umeans unsigned: zero and up, never negative.imeans signed: it can hold a negative number. -
The number is the width in bits.
So u8 is an unsigned 8-bit number, and i32 is a signed 32-bit number. The width fixes how many different values the type can hold, and that fixes the range:
| Type | Bits | Range |
|---|---|---|
u8 | 8 | 0 to 255 |
i8 | 8 | to 127 |
u16 | 16 | 0 to 65535 |
i16 | 16 | to 32767 |
u32 | 32 | 0 to 4294967295 |
i32 | 32 | to 2147483647 |
u64 | 64 | 0 to 18446744073709551615 |
i64 | 64 | to 9223372036854775807 |
Writing a Number with Its Type
There are two places to say which type a number is.
let a: u8 = 5; // the type is on the variable
let b = 5u8; // the type is on the number
Both lines make the same 8-bit value. The letters written straight after a number are called a suffix. 5u8 is read as “5, as a u8”. There is no space before the suffix and no space inside it.
You may put an underscore anywhere in a number to make it easier to read. The compiler ignores it, so 5_u8 is 5u8, and 1_000u16 is 1000u16.
You may also write the number in binary instead of decimal. Start it with 0b, and group the bits in fours with underscores:
let a = 0b0000_0101u8; // the same value as 5u8
Numbers and Their Binary Form
Each row below is a number as you write it in Rust, then the bits the machine stores. The number of columns of bits is the width of the type, and nothing else changes it.
| What you write | Type | Bits | Value |
|---|---|---|---|
5u8 | u8 | 0000 0101 | 5 |
5_u8 | u8 | 0000 0101 | 5 |
0b1010u8 | u8 | 0000 1010 | 10 |
200u8 | u8 | 1100 1000 | 200 |
0b1111_1111u8 | u8 | 1111 1111 | 255 |
5i8 | i8 | 0000 0101 | 5 |
-5i8 | i8 | 1111 1011 | |
5u16 | u16 | 0000 0000 0000 0101 | 5 |
1_000u16 | u16 | 0000 0011 1110 1000 | 1000 |
Read the first three rows together. 5u8, 5_u8 and 0b0000_0101u8 are three ways of writing one value. They store the same eight bits.
Now read 5u8 against 5u16. The value is 5 in both. The u16 holds it in sixteen columns instead of eight, so it is a different amount of memory holding the same number.
You can print the bits of a variable yourself. println!("{a:08b}") prints a in binary, eight wide, so 5u8 comes out as 00000101. Use it to check any answer in this lesson once Rust is installed on your machine.
A Number That Does Not Fit
The suffix also sets a limit. A u8 stops at 255, so this does not compile:
let x = 256u8;
error: literal out of range for `u8`
--> src/main.rs:2:13
|
2 | let x = 256u8;
| ^^^^^
|
= note: the literal `256u8` does not fit into the type `u8`
whose range is `0..=255`
The compiler checks this while it compiles, so a number too large for its type never reaches a running program.
The Width Is Never a Surprise
You choose the width when you declare the variable. Every operation in this lesson works on exactly that many bits — 8 bits for a
u8, 32 bits for ani32. Two operations that look the same can give different answers, because the types are different. Read the type first.
Boolean Logic
Boolean logic is the simplest kind of logic a computer understands. It has only two possible answers: true and false. In Rust these are the two values of the type bool, and they are written true and false.
AND, OR and NOT
There are only three operations:
-
AND — true only when both inputs are true.
-
OR — true when at least one input is true.
-
NOT — flips its input. It takes one input, not two.
Here is the truth table for the three. It shows every possible combination of the inputs and , and what each operation answers:
A && B | A || B | !A | ||
|---|---|---|---|---|
| false | false | false | false | true |
| false | true | false | true | true |
| true | false | false | true | false |
| true | true | true | true | false |
De Morgan’s Law
This is the one Boolean rule worth memorising, because it is used every time a condition has to be negated:
| NOT ( AND ) = (NOT ) OR (NOT ) |
| NOT ( OR ) = (NOT ) AND (NOT ) |
In words: when a NOT is pushed inside a bracket, it flips both terms and swaps AND with OR.
Key idea
De Morgan’s Law turns a negated AND into an OR of two negations. This lets a short-circuiting OR stop as soon as the first condition fails, skipping the second check completely while still giving the same result.
Logical Operators in Rust
The logical operators do not ask “what do these bits look like”. They ask “is this true”. There are three, and they match the three Boolean operations exactly. Both sides must be a bool, and the answer is a bool.
&& — Logical AND
True when both sides are true. Take these two variables:
let age: u32 = 20;
let has_id: bool = true;
| Expression | Is | |
|---|---|---|
age >= 18 | true | a comparison gives a bool |
has_id | true | already a bool |
age >= 18 && has_id | true | both sides true |
Change either side and the whole thing collapses. With age = 15 the first part is false, so age >= 18 && has_id is false too.
|| — Logical OR
True when at least one side is true. Take a day number, where 6 is Saturday and 7 is Sunday:
let day: u8 = 6;
| Expression | Is | |
|---|---|---|
day == 6 | true | |
day == 7 | false | |
| `day == 6 | day == 7` |
! — Logical NOT
Flips a bool. It only accepts a bool, and it gives back a bool:
| Expression | Is |
|---|---|
!true | false |
!false | true |
!has_id | false (has_id was true) |
!(day == 7) | true (day was 6) |
Short-Circuit Evaluation
&& and || stop early. If the left side of && is false, the answer is already false, so the right side is never run. If the left side of || is true, the answer is already true, so the right side is never run. This matters when the right side does real work, or could fail.
Bitwise Operators in Rust
A bitwise operator takes two numbers, lines up their bits, and applies a simple true/false rule to each pair of bits on its own. The bits never influence each other. Nothing carries across, the way it does in addition.
Both sides must be the same integer type, and the answer has that type too. The examples below all use u8, so every number is 8 bits wide:
let a: u8 = 5; // 0000 0101
let b: u8 = 3; // 0000 0011
& — Bitwise AND
A bit in the answer is 1 only when both input bits are 1.
a | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | |
|---|---|---|---|---|---|---|---|---|---|
& b | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | |
a & b | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0000 0001 = 1 |
| — Bitwise OR
A bit in the answer is 1 when at least one input bit is 1.
a | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | |
|---|---|---|---|---|---|---|---|---|---|
| ` | b` | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 |
| `a | b` | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 |
^ — Bitwise XOR
XOR is short for exclusive or. A bit in the answer is 1 when the two input bits are different, and 0 when they are the same.
a | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | |
|---|---|---|---|---|---|---|---|---|---|
^ b | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | |
a ^ b | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0000 0110 = 6 |
<< — Left Shift
Slide every bit to the left and feed in zeros on the right:
a | 0000 0101 | = 5 |
a << 1 | 0000 1010 | = 10 |
a << 2 | 0001 0100 | = 20 |
Each shift to the left doubles the number, because every bit moves into a column worth twice as much. x << n is .
That is true only while the bits still fit. The type has a fixed width, and a bit shifted past the left-hand end is thrown away:
5u8 << 6 | 0100 0000 | = 64 (the top bit fell off) |
5u32 << 6 | 0000 0001 0100 0000 | = 320 |
The u32 has room for the ninth bit, so it keeps the full answer of 320. The u8 has only 8 columns, so the ninth bit has nowhere to go.
>> — Right Shift
The same in reverse. Bits fall off the right-hand end and are lost:
20u8 | 0001 0100 | = 20 |
20u8 >> 2 | 0000 0101 | = 5 |
5u8 >> 1 | 0000 0010 | = 2 (not 2.5) |
x >> n is whole-number division by . The remainder is not rounded. It is shifted off the end and gone.
Two Jobs for
&and|
&&and||work onboolvalues and stop early.&and|work on the bits of an integer and always look at both sides. They are different operators. Writing one where you meant the other is a common mistake, and onboolvalues Rust accepts both, so the compiler will not always catch it.
Bitwise NOT and the Width of the Type
Rust writes bitwise NOT as !, the same symbol as logical NOT. There is no ~ operator in Rust. Which one you get depends on the type of the value:
| Type of the value | What ! does | Result |
|---|---|---|
bool | logical NOT: flips true and false | a bool |
| an integer type | bitwise NOT: flips every bit | the same integer type |
! Flips Every Bit the Type Has
This is the part that catches people out. ! does not flip the bits you were thinking about. It flips all of them, right up to the width of the declared type. So the answer depends on the type, not on the number:
| Bits | Value | |
|---|---|---|
5u8 | 0000 0101 | 5 |
!5u8 | 1111 1010 | 250 |
5i8 | 0000 0101 | 5 |
!5i8 | 1111 1010 | -6 |
Look carefully. !5u8 and !5i8 produce the same eight bits. The values are different because the types read those bits differently. A u8 has no sign, so 1111 1010 counts up to 250. An i8 is signed, so the leading 1 makes it a negative number, and it reads as .
Now change the width instead of the sign:
| Bits | Value | |
|---|---|---|
5i32 | 0000 0000 0000 0000 0000 0000 0000 0101 | 5 |
!5i32 | 1111 1111 1111 1111 1111 1111 1111 1010 | -6 |
!5i8 and !5i32 both give , but they are not the same value in memory. One is 8 bits wide and one is 32. Only the type tells you which.
Read the Type Before You Predict the Answer
!5u8is 250.!5i8is .!5i32is in 32 bits. The expression looks identical every time. The type is the only thing that decides the answer, so it is the first thing to look at.
Negative Numbers in 2’s Complement
A computer stores only bits. There is no minus sign in hardware, so a way is needed to write a negative number using bits alone. The method is called 2’s complement, and it is what every signed Rust type uses.
In a signed type the leftmost bit is the sign bit:
Sign bit 0 | the number is zero or positive |
Sign bit 1 | the number is negative |
An unsigned type has no sign bit. Every bit in a u8 counts towards the value, which is why a u8 reaches 255 and an i8 stops at 127.
Storing a Negative Number
Take i8, a signed 8-bit number. The recipe has two steps. Start from the positive value, flip every bit, then add 1. Here is :
| Start with 5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | |
| Flip every bit | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | |
| Add 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | this is -5i8 |
Checking the Answer
The check is addition. If 1111 1011 really is , then adding it to 0000 0101 must give zero. Add the columns as usual, carrying to the left:
5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | |
|---|---|---|---|---|---|---|---|---|---|
+ (-5) | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | |
= 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | the 9th carry bit falls off the end |
The carry out of the top column has nowhere to go in 8 bits, so it is thrown away. What is left is exactly 0.
Flip and Add 1 Is Also
!Plus 1The first step of the recipe is bitwise NOT.
!5i8gives1111 1010, and adding 1 gives1111 1011, which is . That is why!5i8came out as earlier: flipping the bits lands you one short of the negative value, every time.
Examples 1: Decimal to Binary
Examples 2: Binary to Decimal
10010110
| Place value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|---|
| Power | ||||||||
| Bits | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 0 |
| Worth | 128 |
10010110 = 150
00111111
| Place value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|---|
| Power | ||||||||
| Bits | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
| Worth | 0 |
00111111 = 63
11001000
| Place value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|---|
| Power | ||||||||
| Bits | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 |
| Worth | 128 |
11001000 = 200
01001101
| Place value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|---|
| Power | ||||||||
| Bits | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 |
| Worth | 0 |
01001101 = 77
01100100
| Place value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|---|
| Power | ||||||||
| Bits | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 |
| Worth | 0 |
01100100 = 100
00101000
| Place value | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|---|
| Power | ||||||||
| Bits | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
| Worth | 0 |
00101000 = 40
Check what stuck
The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →