Bit Manipulation

Two's Complement

Two's complement is a negative form of decimal numbers. The 2’s complement of a number is equal to the complement of that number plus 1.

The one's complement or Bitwise NOT operator (~) is a process where, after converting the decimal number to binary, switching 1s to 0s and 0s to 1s.

NOT x=x1\text{NOT }x=-x-1

Note: the size of a byte is 8 bits, and the foremost bit of those bits is the sign bit (Most Significant Bit) that determines the sign. Therefore, we will consider based on the smallest unit of a byte, which is 1 byte or, in other words, 8 bits, rather than thinking in terms of 4 bits.

Shift Operator

The shift operator is an operator that moves the bianry bits in the corresponding direction.

10 in binary bits

For 10 >> 2, if you convert the decimal integer 10 into binary and then shift it two places to the right, and convert this binary back into decimal, you get 40. 10 << 2 can be seen as 10 multiplied by 2 power of 2. In other words, the formula x << n equates to x×2nx\times{2^n}.

10 >> 2

For 10 << 4, if you convert the decimal integer 10 into binary and then shift it four places to the left. However, if the shift operator moves a value beyond its allowable range, it becomes a nonexistent value - data loss occurs.

10 << 4

Bitwise Operator

In boolean operation, 1 should be represented as True, and 0 should be represented as False.

  • The bitwise AND operator (&) results in 1 only if both are 1; if either is 0, the result is 0.

  • The bitwise OR operator (|) results in 1 if at least one of them is 1; it only results in 0 if both are 0.

  • The bitwise XOR (^), which results in 0 if both values are the same and 1 if they are different.

Arithmetic Operation

>>> bin(0b0000000000000101 ^ ~0b0000000000001100)
'-0b1010'

Last updated