2014-02-08 82 views
0

我正在尋找關於如何格式化二進制數字的建議,以便在每隔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

展示如何生成你現在* *的*(字符串的數字)。 – WhozCraig

+0

已更新。謝謝 – user3000731

回答

0

那麼一種方法是將此二進制數字轉換爲字符串變量,然後在每個第四和第五位之間加上一個空格。 Here是如何將int轉換爲字符串的技巧。

1

嘗試這些變化:count++;前右

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

,並添加以下到您的循環:

您的malloc更改爲

/* if i is non-zero and a multiple of 4, add a space */ 
if (i && !(i & 3)) { 
    count++; 
    *(pointer + count) = ' '; 
} 
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]); 
} 
+0

http://stackoverflow.com/questions/11644362/bitwise-operation-on-signed-integer – user3125367

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; 
}