bit-manipulation
Bit Manipulation
Bit masking
Get
set
clear
toggle
Binary numbers
Binary numbers are base-2

101101 = 45
Addition

0110 + 0010 = 1000 or 6 + 2 = 8
Add from right to left ,
If is 1+1 = 2 , becomes 0 and add 1 to next column (left)
Subtraction

0110 - 0011 = 0011 or 6 - 3 = 3
Subtract from right to left
If it is 0 - 1 , borrow from left

Multiplication

00110101 = 1111 or 35 = 15
0011 is the multiplicand
0101 is the multiplier
Multiply from right to left the multiplier digit to the mulitplicand digits
Make sure that each multiplied result is in it corresponding places
Sum the multiplied results
Division
???????
AND
Bitwise AND Operator
&
Returns 1 if both the bits are 1 else 0.

OR
Bitwise OR Operator
|
Returns 1 if either the bits are 1 else 0.

NOT
Bitwise OR Operator
~
Inverse the bits

XOR
Bitwise OR Operator
^
Returns 1 if only one of the bits is 1

Left Shift
Bitwise left shift operator
<<
Shift bits to left and fills right with 0

Shifting a single bit to the left by one place doubles its value


Right Shift
Bitwise left shift operator
Shift bits to right and delete those values that fall off

Shifting a single bit to the right by one place halfs its value


Signed vs Unsigned numbers
Signed ( either positive or negative )
Left most bit is the sign bit
0 means positive
1 means negative
Unsigned ( only positive )
2’s complement
Why? Because using Sign-Magnitude method is only good for representing positive and negative numbers , and but does not work well in computating them(addition, subtraction)

Write out the positive of number
Invert the bits , add 1
Add sign bit to front

Negative number
Last updated