簡體   English   中英

將C中的Char轉換為Binary

[英]Conversion of Char to Binary in C

我正在嘗試將字符轉換為其二進制表示形式(因此,字符-> ascii十六進制->二進制)。

我知道要做到這一點,我需要移動AND 但是,由於某些原因,我的代碼無法正常工作。

這就是我所擁有的。 *temp指向C字符串中的索引。

char c;
int j;
for (j = i-1; j >= ptrPos; j--) {
    char x = *temp;
    c = (x >> i) & 1;
    printf("%d\n", c);
    temp--;
}

我們展示了兩個將單個字符打印為二進制的函數。

void printbinchar(char character)
{
    char output[9];
    itoa(character, output, 2);
    printf("%s\n", output);
}

printbinchar(10)將寫入控制台

    1010

itoa是一個庫函數,可將單個整數值轉換為具有指定基數的字符串。 例如... itoa(1341,output,10)將寫入輸出字符串“ 1341”。 當然itoa(9,output,2)將寫在輸出字符串“ 1001”中。

下一個函數將把一個字符的完整二進制表示形式輸出到標准輸出中,也就是說,如果較高的位為零,它將打印所有8位。

void printbincharpad(char c)
{
    for (int i = 7; i >= 0; --i)
    {
        putchar( (c & (1 << i)) ? '1' : '0' );
    }
    putchar('\n');
}

printbincharpad(10)將寫入控制台

    00001010

現在,我介紹了一個打印出整個字符串(沒有最后一個空字符)的函數。

void printstringasbinary(char* s)
{
    // A small 9 characters buffer we use to perform the conversion
    char output[9];

    // Until the first character pointed by s is not a null character
    // that indicates end of string...
    while (*s)
    {
        // Convert the first character of the string to binary using itoa.
        // Characters in c are just 8 bit integers, at least, in noawdays computers.
        itoa(*s, output, 2);

        // print out our string and let's write a new line.
        puts(output);

        // we advance our string by one character,
        // If our original string was "ABC" now we are pointing at "BC".
        ++s;
    }
}

但是,請考慮一下itoa不會添加填充零,因此printstringasbinary(“ AB1”)將顯示以下內容:

1000001
1000010
110001

您的代碼非常模糊,難以理解,但是我可以為您提供替代方法。

首先,如果您希望temp遍歷整個字符串,則可以執行以下操作:

char *temp;
for (temp = your_string; *temp; ++temp)
    /* do something with *temp */

術語*temp作為for條件只是檢查您是否已到達字符串的末尾。 如果有,則*temp將為'\\0'NUL ),並且for結束。

現在,在for內,您要查找組成*temp的位。 假設我們打印出這些位:

for (as above)
{
    int bit_index;
    for (bit_index = 7; bit_index >= 0; --bit_index)
    {
        int bit = *temp >> bit_index & 1;
        printf("%d", bit);
    }
    printf("\n");
}

為了使它更通用一點,即將任何類型轉換為位,您可以將bit_index = 7更改為bit_index = sizeof(*temp)*8-1

unsigned char c;

for( int i = 7; i >= 0; i-- ) {
    printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}

printf("\n");

說明:

每次迭代時,通過將其移位並與1進行二進制比較,從字節中讀取最高有效位。

例如,假設輸入值為128,二進制轉換為10000000。將其移位7將得到0000 0001,因此得出最高有效位為1. 0000 0001&1 = 1的結論。在控制台中打印。 下次迭代將得出0 ... 0。

暫無
暫無

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

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