我将二进制转换为十六进制,但我需要带有前导零的输出。我在这个函数中使用这个数字 -> creat(outfile, hexa_num);从 011101110111 我会得到 777 但我需要 0777。这是我的转换函数。有什么建议吗?
char bin_final[]="011101110111";
char *a = bin_final;
int hexa_num = 0;
do {
int b = *a=='1'?1:0;
hexa_num = (hexa_num<<1)|b;
a++;
} while (*a);
最佳答案
很简单,只需使用 strtoul()
和常规snprintf()
,无需重新发明任何东西。
const unsigned long number = strtoul("011101110111", NULL, 2);
char buf[16];
snprintf(buf, sizeof buf, "%04lx", number);
puts(buf);
这会打印
0777
当然,如果您只想打印它,您可以将最后三行折叠成:
printf("%04lx\n", number);
关于c - 十六进制 int 变量 C 中的前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46704693/