简体   繁体   English

十进制数转换为16位二进制(C)

[英]decimal number convert to 16bit binary (C)

I want to convert a decimal number to a 16 bit binary number. 我想将十进制数转换为16位二进制数。
My code does not work at all but I am sure that I did the right steps. 我的代码根本不起作用,但是我确信我做的步骤正确。
Hope for some help. 希望能有所帮助。

#include <stdio.h>
#include <stdlib.h>

const int BIT = 16;

char binaer(int i) {
    char str[BIT];
    int j = 0;
    if(0 <= i && i <= 65535) {
        for(int j = 0; j < BIT + 1; j++) {
            if (i % 2 == 0) {
                str[j] = '0';
            } else {
                str[j] = '1';
            }
            i = i / 2;
        }
    }
    for(int x = BIT - 1; x >= 0; x--){
       printf("%c", str[x]);
    }
}

int main() {

    int value;
    scanf("%d", &value);
    binaer(value);


    return 0;
}

Input: 16
Output: 00001000000000000

First of all the loop in main() is meaningless. 首先, main()的循环是没有意义的。 Call the function once and it's done. 调用一次函数即可。

str is a 16 element char array whose elements can be accessed via indices 0 to 15 . str是一个16元素的char数组,其元素可以通过索引015进行访问。 You accessed the 16 th one resulting in Undefined behavior. 您访问了16号,导致未定义的行为。

%s in printf expects a null terminated char array. printf %s期望以null结尾的char数组。 You didn't provide. 您没有提供。 That's Undefined Behavior again. 这又是未定义的行为。

The function doesn't return anything. 该函数不返回任何内容。 Make the return type void . 使返回类型为void

Inversely printing the binary form is being done. 反向打印二进制格式。 Make sure this is what you want. 确保这是您想要的。 You should print the array in reverse. 您应该反向打印阵列。 After the for loop is done you will print it. for循环完成后,您将打印它。

for(int in = BIT-1; in >= 0; in--){
    printf("%c",str[in]);
}
printf("\n");

The way I printed it, if followed, the null terminator is not needed. 我的打印方式(如果遵循的话)则不需要空终止符。

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

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