Let’s try to transform a binary into a decimal with a simple loop.
Let’s see this example of a bit shift into a decimal display:
#include <stdio.h>
int main()
{
int i;
int j;
i = 0;
j = 1;
printf("%d\n", j);
while (i < 32)
{
j = j << 1;
printf("%d\n", j);
i++;
}
return (0);
}
Let’s compile and execute it:
$ cc main.c && ./a.out
Result:
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
-2147483648
0
I’m seeing some of you saying : “Uh why?”
It’s easy. For this example, D = decimal, B = binary
D 1 = B 1
D 2 = B 10
D 3 = B 11
D 4 = B 100
Some of you start to understand!
Indeed, each bit shift means that we add 1 on the left with only 0 after.
Example in binary:
00000001
00000010
00000100
00001000
00010000
00100000
Etc.
This is equivalent in decimal to:
1
2
4
8
16
32
Etc.