3

I need to create a program that converts one number system to other number systems. I used itoa in Windows (Dev C++) and my only problem is that I do not know how to convert binary numbers to other number systems. All the other number systems conversion work accordingly. Does this involve something like storing the input to be converted using %?

Here is a snippet of my work:

case 2:
        {
            printf("\nEnter a binary number: ");
            scanf("%d", &num);
            itoa(num,buffer,8);
            printf("\nOctal        %s",buffer);
            itoa(num,buffer,10);
            printf("\nDecimal      %s",buffer);
            itoa(num,buffer,16);
            printf("\nHexadecimal  %s \n",buffer);
            break;
        }

For decimal I used %d, for octal I used %o and for hexadecimal I used %x. What could be the correct one for binary? Thanks for future answers!

4
  • 1
    Essentially a duplicate of: stackoverflow.com/questions/2343099/… Commented Oct 13, 2012 at 3:41
  • 2
    Short answer: there is none. About all you can do is read a string (e.g., with %s) then convert (e.g., with strtol). Commented Oct 13, 2012 at 3:49
  • 1
    You know itoa is non-standard and it may break on other system? Commented Oct 13, 2012 at 3:56
  • Thanks for answers! Yeah, I know that. We have a project on number systems conversion and our teacher will check this on a compatible system. Commented Oct 13, 2012 at 12:56

1 Answer 1

0

You already have that number in binary form, in memory. Those %d, %o and %x are just as hints for printf-like functions to know how to interpret an argument and convert it between decimal/octal/hexadecimal representations. There is no binary format for printf. Instead you can iterate over all individual bits, like this:

for(int i = 0; i < sizeof(num)*8; i++)
{
    printf("%u", !!(byte & (1 << i)));
}
printf("\n");

This will print all bits of a byte(s), starting from left.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.