我正在寻找有关如何格式化二进制数的建议,以便每隔4位后就有一个空格。我有一个C程序,将十进制数转换为二进制数,但它只给出一个长字符串,没有像“10000000”这样的空格,我希望它是“1000 0000”
编辑:这是代码
1 #include "binary.h"
2
3 char* binary(int num)
4 {
5 int i, d, count;
6 char *pointer;
7
8 count = 0;
9 pointer = (char*)malloc(32+1);
10
11 if(pointer == NULL)
12 exit(EXIT_FAILURE);
13
14 for (i = 31; i >= 0; i--)
15 {
16 d = num >> i;
17
18 if (d & 1)
19 *(pointer + count) = 1 + '0';
20 else
21 *(pointer + count) = 0 + '0';
22
23 count++;
24 }
25 *(pointer+count) = '\0';
26
27 return pointer;
28 }
答案 0 :(得分:1)
尝试以下更改:
将您的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) = ' ';
}
答案 1 :(得分:0)
一种方法是将此二进制数转换为字符串变量,然后在每个第四和第五位之间放置一个空格。 Here是如何将int转换为字符串的提示。
答案 2 :(得分:0)
#include <stdio.h>
#include <string.h>
void
printbin(unsigned v)
{
size_t e = sizeof(v) * 10;
char s[e+1];
s[e--] = 0;
for (; v || e % 5; v >>= 1) {
if (e % 5 == 0) s[e--] = ' ';
s[e--] = (v & 1) ? '1' : '0';
}
printf("%s\n", &s[e+1]);
}
答案 3 :(得分:0)
#include <limits.h>
char* binary(int num){
int i, count, bits = sizeof(num)*CHAR_BIT;
char *pointer = malloc(bits + (bits / 4 -1) + 1);//for bit, for space, for EOS
if(pointer == NULL){
perror("malloc at binary");
exit(EXIT_FAILURE);
}
count = 0;
for (i=bits-1; i >= 0; i--){
pointer[count++] = "01"[(num >> i) & 1];
if(i && (count+1) % 5 == 0)
pointer[count++] = ' ';
}
pointer[count] = '\0';
return pointer;
}