0

My program is meant to convert decimal to binary by reading values from an input file and then outputting the binary values into an output file. Lets say the input file has these numbers:

190 31 5 891717742

Everything converts to binary just fine except for the 891717742. This outputs a value which is completely off of the binary output. Ive tried a LONG but they just output a negative value. For example this would output:

11000100 11110010 11 "1434923237" <- not right (not the actual binary values)

Decimal to Binary (from online):

char* convertDecimalToBinary(int n)
{
  int binaryNumber = 0;
  int remainder, i = 1;
  static char buff[100];

    while (n!=0)
    {
        remainder = n%2;

        n /= 2;
        binaryNumber += remainder*i;
        i *= 10;
    }
    sprintf(buff, "%d", binaryNumber );
    return buff;
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43

2 Answers2

1

The fundamental problem is that you're trying to use an int to store your binary representation. An int is just that, an integer. In memory it's represented in binary, but the C syntax allows you to use base 10 and base 16 literals when assigning or doing other operations on ints. This might make it seem like it's not being treated as a binary number, but it really is. In your program you are confusing the base 2 representation and the base 10 representation. 891717742 (base 10) converted to binary is 110101001001101000100001101110. What your algorithm is essentially trying to do is store the base 10 number 110101001001101000100001101110 in an int. That base 10 number is larger than even a 64 bit number, it would actually would take 97 bits to store.

Check it this answer to see how you can print out the binary representation of an int in C: Is there a printf converter to print in binary format?

bobshowrocks
  • 329
  • 1
  • 6
-1

It is pretty much easy, can be done in two easy steps.

  1. Int to hex string
int main()
{
    int n=891717742;
    char buff[100];
    sprintf(buff, "%x", n);
    printf("\n buff=%s", buff);
    return 0;
}
  1. Hex to binary

Please look at this How to convert a hexadecimal string to a binary string in C

Umair
  • 336
  • 1
  • 16