Decimal to Binary Conversion - Bitwise Left shift operator
It is a number system conversion from decimal to binary, which is implemented by bitwise left shift operator. The left-shift operator shifts the bits of the decimal value towards left direction. it removes MSB bits and adds bits 0s on LSB of the decimal value.
Decimal to Binary Conversion by Left-shift -Manual calculation
Given decimal value =19, converts into binary bits.
on each iteration, AND (bitwise operation ) with the decimal value and 128, if condition is true, returns 1, otherwise 0, the decimal left shift by 1 , resultant value stored on the same decimal value.
n | (decval AND 128) Operation | Decval = decval << by 1 |
---|---|---|
0 | bit[0] = (19 AND 128) ? 1:0 | 38 = 19 <<1 |
1 | bit[1] = (38 AND 128) ? 1:0 | 76 = 38 <<1 |
2 | bit[2] = (78 AND 128) ? 1:0 | 152 = 38 <<1 |
3 | bit[3] = (152 AND 128) ? 1:0 | 304 = 152 <<1 |
4 | bit[4] = (304 AND 128) ? 1:0 | 608 = 304 <<1 |
5 | bit[5] = (608 AND 128) ? 1:0 | 1216 = 608 <<1 |
6 | bit[6] = (1216 AND 128) ? 1:0 | 2432 = 1216 <<1 |
7 | bit[7] = (2432 AND 128) ? 1:0 | 4864 = 2432 <<1 |
results of the decimal=19 into binary bits is 00010011.
Decimal to binary conversion by Left-shift Operator - Pseudocode
Declaration | |
Input | Read integer decval |
Output | char bits[9] |
Temp var | integer n=0,char abit |
Loop | n less-than 8 |
bits[n] = decval AND 128 then '1' else '0' | |
decval left shift by 1 | |
n=n+1 | |
End Loop | |
Output | print,bits |
Decimal to Binary Left-shift - C programming code
The c programming code converts a decimal value into binary bits using left-shift operator. The decimal value (integer) is read from user while the program running and returns its binary 8 bits as result.
#include <stdio.h>
#include <string.h>
int main() {
unsigned int decval;
char bits[9]; int n=0;
printf ("\n Bitwise Left-shift Operator Binary Conversion");
printf("\n Enter a Decimal value :" );
scanf("%u", &decval);
while ( n < 8) {
bits[n]= (decval & 128) ? '1' :'0';
decval = decval <<1;
n++;
}
bits[n] ='\0';
printf("Binary bits :%s",bits);
return 0;
}
Output
Bitwise Left-shift Operator Binary Conversion Enter a Decimal value : 10 Binary bits : 1010
Related post
- Decimal to binary using arithmetic operator
- Binary to decimal using arithmetic operator
- Decimal to 8 bit binary using arithmetic operator
- Decimal to binary using bitwise right-shift operator
- Binary to Decimal using bitwise right-shift operator
- Binary to Decimal using bitwise left-shift operator
- Octal to Binary number system conversion
- Binary to Octal number system conversion
- Hexadecimal to Binary number system conversion
- Binary to Hexadecimal number system conversion
Comments
Post a Comment