Home > Enterprise >  Converting a decimal to a binary in C (output missing digits)
Converting a decimal to a binary in C (output missing digits)

Time:01-14

Why is it returning 7 digits instead of 8 digits once binary array's length is 8 (meaning 8 bits)?

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    int number = get_int("Number: ");
    char binary[8]; // 8 bits in a byte

    for (int i = 0; number != 0 ; i  )
    {
        if (number % 2 == 0)
        {
            binary[i] = '0';
        }
        else
        {
            binary[i] = '1';
        }
        number /= 2;
    }
    printf("%s\n", binary);
}

I'm getting

Number: 72

Binary: 0001001

I know it's reversed from the correct answer for this decimal, just want to correct the missing digit first.

CodePudding user response:

For your program, I only had to make one small correction:

https://ideone.com/87v18W

int main(void)
{
    int number = 145;
    char binary[8 1] = {}; // 8 bits in a byte,   1 for string-terminator
    // If you're going to print it out as a string, you have to make sure there is space for a nil-terminator ('\0') at the end of the string.
    // Hence the  1 for space, and the ={}; to set the whole thing to 0 before filling in the bits.

    for (int i = 0; number != 0 ; i  )
    {
        if (number % 2 == 0)
        {
            binary[i] = '0';
        }
        else
        {
            binary[i] = '1';
        }
        number /= 2;
    }
    printf("%s\n", binary);
}

When I run this program, with input of 145, I get

Output

10001001


Here's how I do ints to binary, with a . separator every 8 bits:

#include <stdio.h>
#include <limits.h>
#include <stdint.h>

int main(void) {
    uint32_t num = 93935;
    
    for(int i=(sizeof(uint32_t)*CHAR_BIT)-1; i>=0; --i)
    {
        printf("%c%s", "01"[!!(num & (1<<i))], i%8?"":i?".":"");
    }
    
    return 0;
}

Example Output:

Success #stdin #stdout 0s 5404KB
00000000.00000001.01101110.11101111
  • Related