How To Convert A Decimal Number To Binary
How To Convert A Decimal Number To Binary
int convert_dec_to_bin ( int num) { int i = 0, j = 0, b[100]; while(num > 0) { b[i]=num % 2; num = num / 2; i++; } printf("\n\nBinary Equivalent:"); j=i-1; for( j= i - 1; j >= 0; j-- ) printf("%d",b[j]); }
2. Which bitwise operator is suitable for checking whether a particular bit is ON or OFF? Bitwise AND operator.
Example: Suppose in byte that has a value 10101101 . We wish to check whether bit number 3 is ON (1) or OFF (0) . Since we want to check the bit number 3, the second operand for AND operation we choose is binary 00001000, which is equal to 8 in decimal.
The resulting value we get in this case is 8, i.e. the value of the second operand. The result turned out to be a 8 since the third bit of operand was ON. Had it been OFF, the bit number 3 in the resulting bit pattern would have evaluated to 0 and complete bit pattern would have been 00000000. Thus depending upon the bit number to be checked in the first operand we decide the second operand, and on ANDing these two operands the result decides whether the bit was ON or OFF.
Code For example need to check whether 3rd bit is ON or OFF Mask for 3rd bit 00001000 (0x08) void check(int num) { if(num & 0x08) printf ("Bit is Set"); else printf ("Bit is NOT Set"); } int main( ) { int num = 100; check(num); } 3. Which bit wise operator is suitable for turning ON a particular bit in a number?
Example: To unset the 4th bit of byte_data or to turn off a particular bit in a number.
Explanation: Consider, char byte_data= 0b01000111; byte_data= (byte_data) | (1<<4); 1 can be represented in binary as 0b00000001 = (1<<4)
<< is a left bit shift operator, it shifts the bit 1 by 4 places towards left.
3. Which bit wise operator is suitable for turning OFF a particular bit in a number?
Example: To unset the 4th bit of byte_data or to turn off a particular bit in a number.
Explanation: Consider, char byte_data= 0b00010111; byte_data= (byte_data)&(~(1<<4)); 1 can be represented in binary as 0b00000001 = (1<<4)
<< is a left bit shift operator, it shifts the bit 1 by 4 places towards left.
Replacing value of byte_data and ~(1<<4) in (byte_data)&(~(1<<4)); we get (0b00010111) & (0b11101111)
int count (int num) { static int cnt = 0; while(num) { cnt++; num = num & (num 1); } return cnt; }
OR
int count (int num) { static int cnt = 0; while(num) { if(num & 1) cnt ++; num = num >> 1; } return cnt; }