gpt4 book ai didi

c - 格式化二进制数字,每组 4 位数字之间有空格

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:02 25 4
gpt4 key购买 nike

我正在寻找有关如何格式化二进制数的建议,以便在每第 4 位数字后有一个空格。我有一个将十进制数转换为二进制数的 C 程序,但它只给出一个没有空格的长字符串,例如“10000000”,我希望它是“1000 0000”

编辑:这是代码

#include "binary.h"

char* binary(int num)
{
int i, d, count;
char *pointer;

count = 0;
pointer = (char*)malloc(32+1);

if(pointer == NULL)
exit(EXIT_FAILURE);

for (i = 31; i >= 0; i--)
{
d = num >> i;

if (d & 1)
*(pointer + count) = 1 + '0';
else
*(pointer + count) = 0 + '0';

count++;
}
*(pointer+count) = '\0';

return pointer;
}

最佳答案

尝试这些改变:

将您的 malloc 更改为:

pointer = malloc(32+7+1); /* 32 digits + 7 spaces + null */

并在 count++; 之前将以下内容添加到循环中:

/* if i is non-zero and a multiple of 4, add a space */
if (i && !(i & 3)) {
count++;
*(pointer + count) = ' ';
}

关于c - 格式化二进制数字,每组 4 位数字之间有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21651825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com