〰️

Bitwise Operations

TypeQuiz 1 Material

Notes

What is “Bitwise”?

Operations

AND, &

// 4 bit example:
0101 & 0110 = 0100

OR, +, |

// 4 Bit Example
0101 | 0110 = 0111

NOT, Complement, Inversion

XOR, ^

// 4 Bit Example:
0101 ^ 0110 = 0011

NAND, ~(A & B)

// 4 Bit Example:
~(0101 & 0110) = 1011

NOR, ~(A | B)

// 4 bit example:
~(0101 | 0110) = 1000

Shifting

Comprehensive Boolean Functions Truth Table

PQFALSEP AND Q~(P → Q) P AND ~Q~(Q → P) ~P AND QP ≠ Q P XOR QP or Q
00000000
01000111
10001011
11010001
PQP NOR QP == Q ~(P XOR Q)~QQ → P P or ~Q~PP → Q ~P or Q P NAND QTRUE
0011111111
0100001111
1000110011
1101010101

Bit Vectors

Some bit hacks

// Convert trailing 0s to 1s
x = (x-1) | x
// Extracting the least significant 1 bit
x = ((~x)+1) & x

Questions & Answers

How would you set bits 7, 8, and 9 (indexed from 0) of a number? Clear them? Toggle them?

How can you use << and >> to make a mask in more complicated problems?

How can you multiply a number by 8 using bitwise arithmetic?

You are given a 16-bit unsigned binary number, x. To test if bit 8 (numbered from right to left starting at 0) is 1, you could use which of the following:

x & (1<<8) ≠ 0

Why is x = x & ~077 better than x = x & 0177700?

First one is independent of word length(no extra cost...evaluated at compile time)

What does this do? (x >> (p+1-n)) & ~(~0 << n);

/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n) {
    return (x >> (p + 1 - n)) & ~(~0 << n);
}

How would you negate in 2’s complement using bitwise operators and the plus operator?

~x+1