簡體   English   中英

我如何將這個短表示為 C 中帶有空格和 0 的二進制字符串?

[英]How do I represent this short as a binary string with spaces and 0's in C?

我有以下代碼,我試圖以“0000 0000 0000”格式返回一個帶有二進制的字符串。 這有效,除了字符串末尾有一個額外的 0 並且我不知道如何修復它。 所以不是用“0000 0000 1100”來代表12,而是變成“0000 0001 1000”

    void convert_to_binary (short acc, char *bin){
   //char bin[16] = {'0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'};
   /* Copies decimal value to temp variable */  
    short decimal, tempDecimal;  
    int index = 0;  
    tempDecimal = acc;  
    int length = strlen(bin);
    for (index=0; index <19;index++){
        
        if ( index % 4 == 0){
            bin[index] == ' ';
        } else if (tempDecimal!=0){
            bin[index] = (tempDecimal % 2) + '0';  

            tempDecimal /= 2;  
            //index++;  
        } else {
            bin[index] == '0';
        }
    }
    bin[index] = '\0';  

    strrev(bin);  
} // convert acc to binary str for output

一些提示:

  • bin[index] == '0'; 不輸出0因為您使用比較運算符==而不是賦值運算符=
  • 這同樣適用於這一行bin[index] == ' ';
  • 使用並注意編譯器警告,例如使用gcc -Wall -Wextra main.c編譯器會警告上述要點和未使用的變量
  • 您希望每 5 個字符作為空格而不是每 4 個字符,因此使用index % 5而不是index % 4
  • 您的循環條件是index <19 ,它實際上應該是index < 15 ,如果您想輸出三組每組 4 個字符,您可能不希望在這樣的例程中硬編碼這樣的常量
  • 次要:一些庫實現方便地包含strrev ,但如果目標是編寫可移植的 C,您可能不會使用它

如果你應用以上幾點,輸出是你想要的'0000 0000 1100'。

選擇

您也可以從左到右工作。 所以你不需要反轉字符串。 您還可以測試是否通過位移操作結合位測試來設置位,如下所示:

bool n = (acc >> (unsigned)index) & 1u;

對於位操作,建議使用無符號值。 要轉換的位數可能是函數的參數,因此簽名可能如下所示:

void convert_to_binary(unsigned acc, int bits, char *bin) 

循環是基於位數而不是要寫入的字符數,因此在每 4 位輸出后會輸出一個額外的空格字符,因此可以在此處使用% 4

這看起來像這樣:

void convert_to_binary(unsigned acc, int bits, char *bin) {
    char *ptr = bin;
    for(int index = bits - 1; index >= 0; index--) {
        bool n = (acc >> (unsigned)index) & 1u;
        *ptr++ = n ? '1' : '0';
        if(index % 4 == 0)
            *ptr++ = ' ';
    }
    *ptr = '\0';
}

測試

這幾個測試用例:

int main(void) {
    char buf[40] = {0};
    convert_to_binary(0xFFFFFFFF, 32, buf);
    printf("%s\n", buf);
    convert_to_binary(0x7FFFFFFF, 32, buf);
    printf("%s\n", buf);
    convert_to_binary(1, 32, buf);
    printf("%s\n", buf);
    convert_to_binary(0, 32, buf);
    printf("%s\n", buf);
    convert_to_binary(12, 32, buf);
    printf("%s\n", buf);
    convert_to_binary(12, 12, buf);
    printf("%s\n", buf);
    return 0;
}

將給出以下輸出:

1111 1111 1111 1111 1111 1111 1111 1111 
0111 1111 1111 1111 1111 1111 1111 1111 
0000 0000 0000 0000 0000 0000 0000 0001 
0000 0000 0000 0000 0000 0000 0000 0000 
0000 0000 0000 0000 0000 0000 0000 1100 
0000 0000 1100 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM