Bitwise Operators (and BSets) Flashcards
1
Q
How to add to a bitset
A
- Create a binary value with the specific position set as 1
In python: 1 «_space;(item - 1) - meaning, take 1 bit, and move it left (item-1) positions - Then use the OR operator |= against the bitset, to actually update the value
2
Q
How to remove an element from a bitset
A
- Create a binary value with the specific position set as 1
In python: 1 «_space;(item - 1) - Then use the XOR operator ^= against the bitset
XOR, exclusive OR, an output bit is 1 when the elements are different, and 0 when the elements are the same
3
Q
How to check if an element is in a bitset
A
Take the elements, shift it right to the element u wish to check, so elems»_space; (item - 1)
And then AND it against 0001, which will check if the right most bit is 1, and if it is, then the element is in the bitset
4
Q
How to calculate the length of a bitset
A
You need to get the bitlength, and then loop through and check if the element is in the bitset
so O(|elements|) or O(num of elems)