在C语言中将字符转换为二进制

7

我正在尝试将字符转换为其二进制表示(即字符 -> 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--;
}

ptrPos是什么意思?i是什么意思? - Hogan
听起来你正在尝试将一个单一的字符转换为二进制,在这种情况下相当简单,这意味着你不需要一个指针(那是没有任何意义的),你只需要通过位移进行比特检查并检查它是否为1(与1进行AND操作)。看一下Salvatore的第二个代码片段。 - AusCBloke
你能给我们展示一两个具体的输入和输出的例子吗? - Keith Thompson
3个回答

37

我们展示了两个函数,打印单个字符的二进制表示。

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

2
从技术上讲,应该是 i = CHAR_BIT - 1。你知道的,为了适应那些9位和11位处理器。 - Chris Lutz
1
这是错误的。itoa函数需要一个整数,而你正在传递一个字符*s。 - darksky
2
不是错误。*s 表示字符串 s 指向的第一个字符。在 C 中,字符只是 8 位整数(现今如此)。 - Salvatore Previti
1
itoa(10, output, 2) 将会把字符串 "1010" 写入到 output 字符串中。 - Salvatore Previti
1
printbincharpad(10) 将会在控制台输出字符串 "00001010"。 - Salvatore Previti
显示剩余2条评论

5
unsigned char c;

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

printf("\n");

解释:

在每次迭代中,通过将字节向左移位并与1进行二进制比较来读取最高有效位。

例如,假设输入值为128,其二进制为1000 0000。 将其向左移动7位将会得到0000 0001,因此可以得出结论,最高有效位为1。0000 0001 & 1 = 1。这是要在控制台打印的第一位。下一次迭代将结果为0 ... 0。


3
你的代码非常含糊,难以理解。但我可以为你提供一个替代方案。
首先,如果你想让 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接