HomeAbout Me

Bit Manipulation

By Daniel Nguyen
Published in Algorithm
April 10, 2024
1 min read
Bit Manipulation

AND

Only true if both input bits are true:

//0 & 0 = 0
//1 & 0 = 0
//0 & 1 = 0
//1 & 1 = 1

OR

True if any input bit is true

//0 | 0 = 0
//1 | 0 = 1
//0 | 1 = 1
//1 | 1 = 1

XOR

True if one and only one input bit is true

//0 ^ 0 = 0
//1 ^ 0 = 1
//0 ^ 1 = 1
//1 ^ 1 = 0

NOT

Flip the input bit:

//-1 = 0
//-0 = 1

Left Shift

Shift left the binary digits by n, pad 0’s on the right

//00010110 << 3
//= 10110000

Right Shift

Shift right the binary digits by n, pad 0’s on the left

//00010110 >> 3
//= 00000010

Get Bit

get_bit(x, position) = (x >> position) & 1
//position is counted from right to left, start from 0.
position = 6, x = 01100110
get_bit(x, 6) = 1
get_bit(x, position) = (01100110>>6) & 1 = (00000001) & (00000001) = 1

Set Bit

set_bit(x, position):
mask = (1<<position)
return (x | mask)
//position = 5
//x = 00010110
//mask = 0010000
//res = 00110110

Flip Bit

flip_bit(x, position):
mask = (1<<position)
return x ^ mask

Tags

#Algorithm

Share

Previous Article
Big “Oh” notation
Next Article
Array

Table Of Contents

1
AND
2
OR
3
XOR
4
NOT
5
Left Shift
6
Right Shift
7
Get Bit
8
Set Bit
9
Flip Bit

Related Posts

Hash Table
April 26, 2024
1 min
© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media