如何将转换的char存储为二进制数

问题描述 投票:2回答:3

我想你们已经听说过像这样的代码了

   (c & (1 << i)) ? '1' : '0';

我已经将它存储在一个数组上,但它给了我一个错误的二进制文件。这是附加代码

int i;
char test[8];
for(i=7 ; i>=0; i--){

    test[i] =(c &(1 << i)) ? '1' : '0';
}
int j = atoi(test);
printf("%d\n", j);

我的样本是:'我'它给了我:100100109

c
3个回答
3
投票

atoi(test);的行为未定义。参数test(一旦衰减为指针类型)必须指向一个NUL终止的char数组。你的不是。

写这个解决方案很简单

char test[9] = {0};

而是强制包含NUL终止符。但请注意,结果数字大约为1000万;因此对于int来说可能太大了。使用long来确定,以及atol而不是atoi。如果您希望将字符串解析为二进制,则使用strtol传递2的基数。


0
投票

要将格式为base 2(“binary”)中的字符串的数字转换为实际整数,请使用strtoul()

const unsigned long x = strtoul("11100011", NULL, 2);
printf("x=%lu\n", x);

最后的2指定了基础,2当然给了二进制,这打印227


0
投票

正如在其他答案中已经提到的,核心问题是你没有null终止字符串。但是这个程序还有其他各种不好的做法:

更正的程序可能如下所示:

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

int main (void)
{
  unsigned int c = 100;

  char test[8+1];

  for(size_t i=0; i<8; i++)
  {
    test[i] = c & (1u<<(8-1-i)) ? '1' : '0';
  }
  test[8] = '\0';

  int j = (int)strtol(test, NULL, 10);
  printf("%.8d\n", j);

  return 0;
}

或者,如果你生活和呼吸C语言运算符优先级(主要的书呆子警告),你可能会自大,只需写test[i] = c & 1u << 8-1-i ? '1' : '0';。这里的运算符优先级是:-<<&?:=

© www.soinside.com 2019 - 2024. All rights reserved.