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!

Serge
  • 6,088
  • 17
  • 27
puchu
  • 31
  • 1
  • 2
  • 1
    Essentially a duplicate of: http://stackoverflow.com/questions/2343099/convert-binary-format-string-to-int-in-c – Geoff Montee Oct 13 '12 at 03: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`). – Jerry Coffin Oct 13 '12 at 03:49
  • 1
    You know `itoa` is non-standard and it may break on other system? – nhahtdh Oct 13 '12 at 03: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. – puchu Oct 13 '12 at 12:56

1 Answers1

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.

Zaffy
  • 16,801
  • 8
  • 50
  • 77