简体   繁体   中英

C Converting 4 digit numbers to binary

I want to print the binary equivalent of the numbers from a file in a 20 bit field with spaces after every 4 bits but when the number exceeds 1024 (I've tested this), it no longer outputs in binary but in a base I don't know (ie 1234 = 0000 0014 1006 5408)

Here is my code

#include <stdio.h>
long convertToBinary(long);

int main()
{
    char binNum[20]; //binary number char array
    int i;
    long b, decNum; //b is output binary number, decNum is each input number from file
    FILE *filePtr;
    filePtr = fopen("numbers.txt", "r");
    while (!feof(filePtr))
    {
        fscanf(filePtr, "%li", &decNum);
        if (decNum < 0  || decNum > 65535)
        {
            printf("Error, %5li is out of range.\n", decNum);
            continue;
        }
        b = convertToBinary(decNum); //function call for binary conversion

        i = 18;
        while (i >= 0)
        {
            if (i == 4 || i == 9 || i == 14)
            {
                binNum[i] = ' ';
            }
            else if (b != 0)
            {
                binNum[i] = b % 10 + '0';
                b /= 10;
            }
            else 
            {
                binNum[i] = '0';
            }
            i--;
        }
        binNum[19] = '.';
        printf("The binary representation of %5li is: ", decNum);
        for (i = 0; i<20; i++)
        {
            printf("%c", binNum[i]);
        }
        printf("\n");
    }

return 0;
}

//Recursion function
long convertToBinary(long number)
{
    if (number == 0)
    {
        return 0;
    }
    else
    {
        return (number % 2 + 10 * convertToBinary(number / 2));
    }
}

The file numbers.txt has numbers like : 0 1 2 3 16 17 1234 5678 65535

Your convertToBinary function is producing a decimal-coded-binary (as opposed to a binary-coded-decimal) which uses a decimal digit per bit.

It looks like long has the same range as int on your system, ie 2 31 , which covers ten decimal digits. Once you get eleventh digit, you get an overflow.

Switching to unsigned long long , which has 64 bits, will fix the problem. However, this is sub-optimal: you would be better off writing a to-binary conversion that writes zeros and ones into an array of char s that you provide. You can do it recursively if you'd like, but an iterative solution will do just fine.

Note that the to-binary conversion does not need to insert spaces into char array. This can be done by your main function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM