3/6/08

Simple Decimal to Binary Converter

This is a very simple program written in C to convert decimal numbers to 16bits binary numbers.

#include <stdio.h>

int main(int argc, char *argv[]){
int num,i;
printf("Give number between 0-65535 : ");
scanf("%d",&num);
for (i=15;i>=0;i--) {
if (num & 1<<i)
putchar('1');
else
putchar('0');
}
putchar('\n');
exit(0);
}

As you probably noticed no check is made. User inputs a number between 0 and 65535 and it is converted to a 16 bit binary number.

Now let's explain what the above code does.
Actually I must explain the operator & (Bitwise AND Operator) and I always prefer examples.
if num is 20 then we must get 10100 in binary.
first we bit wise num and 1<<15
0000000000010100
1000000000000000
=
0000000000000000
We only get something != 0 when both numbers have one (1) at the same position.
For the example above we get zeros until we bit wise AND
0..010100
0..010000 (16)
0..010000 != 0 so we print 1

I hope that this explanation help you. If not feel free to leave your comment.

Also, if you are interested, this is a binary to decimal converter.

2 comments:

Anonymous said...

can you make some comments to that? for example what exactly does "if (num & 1 << i)" means? what does it do for the program?
Thanks in advance!

Andreas Papadopoulos said...

I am afraid you are right. I didn't add any comments above. I will edit the post.
Thank you very much.