简体   繁体   English

C中十进制转二进制(输出缺失数字)

[英]Converting a decimal to a binary in C (output missing digits)

Why is it returning 7 digits instead of 8 digits once binary array's length is 8 (meaning 8 bits)?为什么在二进制数组的长度为 8(即 8 位)时返回 7 位而不是 8 位?

#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数量:72

Binary: 0001001二进制:0001001

I know it's reversed from the correct answer for this decimal, just want to correct the missing digit first.我知道它与这个小数的正确答案相反,只是想先更正缺失的数字。

For your program, I only had to make one small correction:对于你的程序,我只需要做一个小的更正:

https://ideone.com/87v18W 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当我运行这个程序时,输入145 ,我得到

Output Output

10001001


Here's how I do ints to binary, with a .下面是我如何使用. separator every 8 bits:每 8 位分隔符:

#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:示例 Output:

Success #stdin #stdout 0s 5404KB
00000000.00000001.01101110.11101111

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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