CourseLesson 1 · Bits, Booleans and Bitwise OperationsSolve

Lesson 01

Bits, Booleans and Bitwise Operations

Goal

By the end of this lesson you will be able to:

  1. Convert a decimal number to binary and back.

  2. Read a number as bits, nibbles and bytes.

  3. Name the width of a Rust integer type from the type itself.

  4. Use the logical operators, which work on a whole value as true or false:

  • && — AND

  • || — OR

  • ! — NOT

  1. Apply De Morgan’s laws when a NOT is involved.

  2. 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

  1. 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:

21326remainder 123remainder 021remainder 10remainder 113 = 1101

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:

DecimalBinaryDecimalBinary
0000081000
1000191001
20010101010
30011111011
40100121100
50101131101
60110141110
70111151111

Binary to Decimal

Each position in binary holds a 0 or a 1, and each position is worth 2n2^n, starting from the right at 202^0. The value of the whole number is the sum of the positions that hold a 1. The positions holding a 0 add nothing.

Example:

1286432168421
272^7262^6252^5242^4232^3222^2212^1202^0
11111011
128+64+ 64+32+ 32+16+ 16+8+ 8+0+ 0+2+ 2+1+ 1== 251

More examples:

000011018+4+1=138 + 4 + 1 = 13
10108+2=108 + 2 = 10
10011100128+16+8+4=156128 + 16 + 8 + 4 = 156

Bits, Nibbles and Bytes

UnitWhat it is
bitOne binary digit: 0 or 1
nibble4 bits — 16 possible values (0–15)
byte8 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. 210=10242^{10} = 1024 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. u means unsigned: zero and up, never negative. i means 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:

TypeBitsRange
u880 to 255
i88−128-128 to 127
u16160 to 65535
i1616−32768-32768 to 32767
u32320 to 4294967295
i3232−2147483648-2147483648 to 2147483647
u64640 to 18446744073709551615
i6464−9223372036854775808-9223372036854775808 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 writeTypeBitsValue
5u8u80000 01015
5_u8u80000 01015
0b1010u8u80000 101010
200u8u81100 1000200
0b1111_1111u8u81111 1111255
5i8i80000 01015
-5i8i81111 1011−5-5
5u16u160000 0000 0000 01015
1_000u16u160000 0011 1110 10001000

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 an i32. 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 AA and BB, and what each operation answers:

AABBA && BA || B!A
falsefalsefalsefalsetrue
falsetruefalsetruetrue
truefalsefalsetruefalse
truetruetruetruefalse

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 (AA AND BB) = (NOT AA) OR (NOT BB)
NOT (AA OR BB) = (NOT AA) AND (NOT BB)

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;
ExpressionIs
age >= 18truea comparison gives a bool
has_idtruealready a bool
age >= 18 && has_idtrueboth 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;
ExpressionIs
day == 6true
day == 7false
`day == 6day == 7`

! — Logical NOT

Flips a bool. It only accepts a bool, and it gives back a bool:

ExpressionIs
!truefalse
!falsetrue
!has_idfalse (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.

a00000101
& b00000011
a & b00000001→\to 0000 0001 = 1

| — Bitwise OR

A bit in the answer is 1 when at least one input bit is 1.

a00000101
`b`00000011
`ab`00000111

^ — 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.

a00000101
^ b00000011
a ^ b00000110→\to 0000 0110 = 6

<< — Left Shift

Slide every bit to the left and feed in zeros on the right:

a0000 0101= 5
a << 10000 1010= 10
a << 20001 0100= 20

Each shift to the left doubles the number, because every bit moves into a column worth twice as much. x << n is x×2nx \times 2^n.

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 << 60100 0000= 64 (the top bit fell off)
5u32 << 60000 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:

20u80001 0100= 20
20u8 >> 20000 0101= 5
5u8 >> 10000 0010= 2 (not 2.5)

x >> n is whole-number division by 2n2^n. The remainder is not rounded. It is shifted off the end and gone.

Two Jobs for & and |

&& and || work on bool values 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 on bool values 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 valueWhat ! doesResult
boollogical NOT: flips true and falsea bool
an integer typebitwise NOT: flips every bitthe 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:

BitsValue
5u80000 01015
!5u81111 1010250
5i80000 01015
!5i81111 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 −6-6.

Now change the width instead of the sign:

BitsValue
5i320000 0000 0000 0000 0000 0000 0000 01015
!5i321111 1111 1111 1111 1111 1111 1111 1010-6

!5i8 and !5i32 both give −6-6, 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

!5u8 is 250. !5i8 is −6-6. !5i32 is −6-6 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 0the number is zero or positive
Sign bit 1the 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 −5-5:

Start with 500000101
Flip every bit11111010
Add 111111011→\to this is -5i8

Checking the Answer

The check is addition. If 1111 1011 really is −5-5, then adding it to 0000 0101 must give zero. Add the columns as usual, carrying to the left:

500000101
+ (-5)11111011
= 000000000the 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 1

The first step of the recipe is bitwise NOT. !5i8 gives 1111 1010, and adding 1 gives 1111 1011, which is −5-5. That is why !5i8 came out as −6-6 earlier: flipping the bits lands you one short of the negative value, every time.

Examples 1: Decimal to Binary

2623remainder 021remainder 10remainder 16 = 110
225212remainder 126remainder 023remainder 021remainder 10remainder 125 = 11001
240220remainder 0210remainder 025remainder 022remainder 121remainder 00remainder 140 = 101000
277238remainder 1219remainder 029remainder 124remainder 122remainder 021remainder 00remainder 177 = 1001101
2100250remainder 0225remainder 0212remainder 126remainder 023remainder 021remainder 10remainder 1100 = 1100100
22002100remainder 0250remainder 0225remainder 0212remainder 126remainder 023remainder 021remainder 10remainder 1200 = 11001000
2924remainder 122remainder 021remainder 00remainder 19 = 1001
263231remainder 1215remainder 127remainder 123remainder 121remainder 10remainder 163 = 111111
2150275remainder 0237remainder 1218remainder 129remainder 024remainder 122remainder 021remainder 00remainder 1150 = 10010110

Examples 2: Binary to Decimal

10010110

Place value1286432168421
Power272^7262^6252^5242^4232^3222^2212^1202^0
Bits10010110
Worth128+0+ 0+0+ 0+16+ 16+0+ 0+4+ 4+2+ 2+0+ 0

128+16+4+2128 + 16 + 4 + 2

10010110 = 150

00111111

Place value1286432168421
Power272^7262^6252^5242^4232^3222^2212^1202^0
Bits00111111
Worth0+0+ 0+32+ 32+16+ 16+8+ 8+4+ 4+2+ 2+1+ 1

32+16+8+4+2+132 + 16 + 8 + 4 + 2 + 1

00111111 = 63

11001000

Place value1286432168421
Power272^7262^6252^5242^4232^3222^2212^1202^0
Bits11001000
Worth128+64+ 64+0+ 0+0+ 0+8+ 8+0+ 0+0+ 0+0+ 0

128+64+8128 + 64 + 8

11001000 = 200

01001101

Place value1286432168421
Power272^7262^6252^5242^4232^3222^2212^1202^0
Bits01001101
Worth0+64+ 64+0+ 0+0+ 0+8+ 8+4+ 4+0+ 0+1+ 1

64+8+4+164 + 8 + 4 + 1

01001101 = 77

01100100

Place value1286432168421
Power272^7262^6252^5242^4232^3222^2212^1202^0
Bits01100100
Worth0+64+ 64+32+ 32+0+ 0+0+ 0+4+ 4+0+ 0+0+ 0

64+32+464 + 32 + 4

01100100 = 100

00101000

Place value1286432168421
Power272^7262^6252^5242^4232^3222^2212^1202^0
Bits00101000
Worth0+0+ 0+32+ 32+0+ 0+8+ 8+0+ 0+0+ 0+0+ 0

32+832 + 8

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 →