BitMask
✅ BitMask
modify numbers into binary representaion
Bit: binary digit, smallest unit for computer
✅ Code
✔️ present in array
1
2
3
4
//array
int[] array1 = [1, 1, 1, 1, 0];
int[] array2 = [1, 1, 0, 1, 0];
int[] array3 = [1, 0, 1, 0, 0];
✔️ present in bitmask
1
2
3
4
5
6
//bitmask
{ 0, 1, 2, 3, 4 } => 11111 = 16 + 8 + 4 + 2 + 1 = 31
{ 1, 2, 3, 4 } => 11110
{ 1, 2, 4 } => 10110
{ 2, 4 } => 10100 = 16 + 4 = 20
{ 1 } => 00010
✔️ modify binary back to decimal
1
2
3
4
5
6
//into decimal
{ 0, 1, 2, 3, 4 } => 11111
{ 1, 2, 3, 4 } => 11110
{ 1, 2, 4 } => 10110
{ 2, 4 } => 10100
{ 1 } => 00010
✔️ Caculators
1
2
3
4
5
6
//1010
//change i=2 to 1
1010 | 1 << 2
//1 << 2 = 100
1010 | 0100 => 1110
✔️ change 1 to 0
1
2
3
4
1110 & ~1 << 2
// ~1 = 1110
// 1110 << 2 = 1011
1110 & 1011 => 1010
💡 Reference
This post is licensed under CC BY 4.0 by the author.