Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i made decimal to binary converter with C. I am very familiar with C and C++, but i always had a hard time understanding bits. The code gives the right binary number for the decimal, the only problem is that it is backwards. I used the >> operator and &. I do not know how to use a mask for this as i still find it confusing. Some advice on that would be nice and i would appreciate it. But i also want to find out how to reverse the numbers, if i was using a mask it would be easy to just use ~, but i am not. Any advice and review would be nice.

Here is the code:

#include <stdio.h>
int main(void)
{
int i;
int dec;

scanf("%d" , &dec);

for(dec; dec > 0; dec = dec>>1)//shifting bits to the right by 1 is equivalent to dividing by power of 2.
{
if(dec & 1)//check least significant bit, if odd, then result is 1
printf("1");

else//if even then result is 0
printf("0");
}
}
Posted

1 solution

Don't use printf bit by bit. Instead, create a string (could be as simple C string, char*) of required length and fill it in reverse order, and then output the string at once. Or shift in opposite direction. Just a bit of thinking and you are done. You should understand that traditional "binary" notation is having least significant bit on right, as with all other bases; and you did the opposite.

Your code is very short. Perhaps you could go a bit longer way, but it can give you better understanding. On each iteration step, create a mask, 1 << index, where index is a bit number. In this mask, you have only one set (1) bit in the position of the current bit number. So, if you AND it with the number to be represented (dec & (1 << index)), it will give you either 0 or non-zero, 0 is the test bit in dec is clear, not-zero if it is set.

And you need to understand that you are not "converting" decimal to "binary". You represent any number as a string showing bit representation. You number, dec, despite your variable name, cannot be "decimal" or "hexadecimal". These concepts are not applicable to numbers. You can consider numbers and all other objects are binary.

Yes, inversion is '~', I don't see a problem.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900