简体   繁体   English

在C中将十进制数转换为二进制

[英]Converting a decimal number to binary in C

I was trying to convert a decimal from [0, 255] to a 8 bit binary number, where each bit will be separated by a comma and a space. 我试图将十进制从[0, 255]转换为8位二进制数,其中每个位将由逗号和空格分隔。 I tried the following (eventually it worked, except for the last bit does not require any separator ): 我尝试了以下操作(最终成功了,除了最后一位不需要任何分隔符):

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

char* atobin(int input) {
    char *str = malloc(0);
    int index, count = 0;
    if (input > 255| input < 0) {
        printf ("Input out of range. Abort.\n");
        exit(EXIT_FAILURE);
    }

    for (index = 7; index >= 0; index--) {
        *(str + (count++)) = (input >> index & 1) ? '1' : '0';
        *(str + (count++)) = ',';
        *(str + (count++)) = ' ';
    }
    *(str + count) = '\0';
    return str;
}

int main(int argc, char *argv[]) {
    printf("%s\n", atobin(atoi(argv[1])));
    return EXIT_SUCCESS;
}

Now I have a few questions: 现在我有几个问题:

  1. I used malloc(0) ; 我用了malloc(0) ; as far as I am concerned, it will allocate no memory from the heap. 就我而言,它将不会从堆中分配任何内存。 So, how/ why is it working? 那么,它如何/为什么起作用?
  2. Is the declaration *(str + count) = '\\0'; 声明*(str + count) = '\\0'; necessary? 必要?
  3. Is there any way to optimize this code? 有什么方法可以优化此代码?

UPDATE 更新

To carry on this experiment, I have taken the atobin function in to a .h file. 为了进行此实验,我将atobin函数atobin一个.h文件中。 This time it creates some problems. 这次它产生了一些问题。 Now I add my last question: 现在,我添加我的最后一个问题:

What should be minimum integer to be used for the parameter of malloc ? malloc参数应使用的最小整数是多少? Some trial-and-error method makes me guess it should me 512 . 一些试错法让我猜测应该是512 Any idea? 任何想法?

  1. From a malloc doc: 从malloc文档中:

If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. 如果size为零,则返回值取决于特定的库实现(它可以是空指针,也可以不是空指针),但是不得取消对返回的指针的引用。

That it works for you is just luck. 它为您工作只是运气。 Try some random malloc and free afterwards and you will have a high probability - but no guarantee - that you will get a crash. 尝试一些随机的malloc并在之后释放它们,那么您很有可能(但不能保证)会崩溃。

  1. This null-terminates the string. 这将以null结尾的字符串。 Depends on how you want to use the string if you need it. 取决于您需要使用字符串的方式。 The printf in your example needs it, because that's the only way for it to know when the string ends. 您的示例中的printf需要它,因为这是它知道字符串何时结束的唯一方法。

  2. I'm sorry, I don't have time to take a closer look. 抱歉,我没有时间仔细看。

malloc(0) is valid to be used. malloc(0)有效使用。 what it returns is implementation defined. 它返回的是实现定义的。 but what happens if you access a object through the pointer returned by malloc(0) is undefined behavoiur . 但是,如果通过malloc(0)返回的指针访问对象会发生undefined behavoiur you can read this related question. 您可以阅读相关问题。
In C since strings are character arrays terminated by \\0 it is better to use *(str + count) = '\\0'; 在C语言中,由于字符串是以\\0结尾的字符数组,因此最好使用*(str + count) = '\\0'; statement to set the last character of string. 设置字符串的最后一个字符的语句。 It is working in this code but its better to set the end of string in code always. 它可以在此代码中运行,但最好始终在代码中设置字符串的结尾。 It may work if bits are set to 0 since it is same as terminating a string. 如果将位设置为0,则可能会起作用,因为它与终止字符串相同。

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

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