Bit Manipulation-DSA Flashcards
how to find binary equivalent of any decimal number
- divide it by 2
how to convert binary to decimal
- 1101 to decimal
- start from right, move towards left
3.
(that number * 2) raise to the power of that index + (that number * 2) raise to the power of that index + (that number * 2) raise to the power of that index
add all numbers
O/p is in decimal…
write a function that will take decimal and return its binary
string count2Binary(int n){
res = “”
while(n != 1){
if (n % 2 == 1) res += “1”
else res += “0”;
n = n/2;
}
reverse(res);
return res;
}
write a function that takes binary and return its decimal equivalent
int convertToDecimal(string x){
int len = x.length();
for(i =len - 1; i–){
if(n[i] == ‘1’)
num = num + p2;
p2 = p2 * 2;
}
return num;
}
===
TC => O(len)
SC => O(1)
what happens when we write
int x = 13
13 gets converted to binary, but 13 requires only 4 bits
13 requires only 13 bits, what happens with other remaining bits
remaining bits will be stored with zero’s
how many bits required to store int
32 bits
if x is stored as binary, when we print int, how does we get int, like 13 in this example
reverse conversion of binary / bits happens, 13 gets converted to binary
int is 32 bits, how many bits for long long
64 bits
===
most of the problems of long long can be solved if you know int concept
what is ones complement.
Que. what is ones complement of 13
13 => (1101)2 base 2
flip all the bits
=> 0010
what is twos complement
step 1: figure out ones complement of number
step 2: add one to it
Que. what is 13’s two complement
- 13 => (1101)base 2
- ones complement => 0010
- add one => 0011
AND operator explain
all true => true
one false => false
x = 13 & 7
= 5
1 1 0 1 => 13
0 1 1 1 => 7
———-
0 1 0 1 => 5
OR operator
one true => true
all false => false
x = 13 | 7
1 1 0 1
0 1 1 1
———-
1 1 1 1 => 15
XOR
number of 1s => odd -> one
number of 1s => even -> zero
right shift operator
x = 13»_space; 1
1101
last one goes off the clip
0000000…110
=> o/p will be 6
x = 13»_space; 2
last two numbers, will go off the clip
000000…11
o/p => 3
x = 13»_space; 4
00000000….1101
0000000000000
all of them go off the clip