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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7863499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:58:25  来源:igfitidea点击:

Conversion of Char to Binary in C

cstringbinarycharascii

提问by darksky

I am trying to convert a character to its binary representation (so character --> ascii hex --> binary).

我正在尝试将字符转换为其二进制表示形式(因此字符 --> ascii 十六进制 --> 二进制)。

I know to do that I need to shift and AND. However, my code is not working for some reason.

我知道这样做我需要转移和AND。但是,由于某种原因,我的代码不起作用。

Here is what I have. *temppoints to an index in a C string.

这是我所拥有的。*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--;
}

回答by Salvatore Previti

We show up two functions that prints a SINGLE character to binary.

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

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

printbinchar(10) will write into the console

printbinchar(10) 将写入控制台

    1010

itoa is a library function that converts a single integer value to a string with the specified base. For example... itoa(1341, output, 10) will write in output string "1341". And of course itoa(9, output, 2) will write in the output string "1001".

itoa 是一个库函数,可将单个整数值转换为具有指定基数的字符串。例如... itoa(1341, output, 10) 将写入输出字符串“1341”。当然 itoa(9, output, 2) 将写入输出字符串“1001”。

The next function will print into the standard output the full binary representation of a character, that is, it will print all 8 bits, also if the higher bits are zero.

下一个函数会将字符的完整二进制表示打印到标准输出中,也就是说,它将打印所有 8 位,如果高位为零也是如此。

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

printbincharpad(10) will write into the console

printbincharpad(10) 将写入控制台

    00001010

Now i present a function that prints out an entire string (without last null character).

现在我提出了一个打印出整个字符串(没有最后一个空字符)的函数。

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

Consider however that itoa don't adds padding zeroes, so printstringasbinary("AB1") will print something like:

但是请考虑 itoa 不添加填充零,因此 printstringasbinary("AB1") 将打印如下内容:

1000001
1000010
110001

回答by Shahbaz

Your code is very vague and not understandable, but I can provide you with an alternative.

您的代码非常模糊且无法理解,但我可以为您提供替代方案。

First of all, if you want tempto go through the whole string, you can do something like this:

首先,如果你想temp遍历整个字符串,你可以这样做:

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

The term *tempas the forcondition simply checks whether you have reached the end of the string or not. If you have, *tempwill be '\0'(NUL) and the forends.

*temp作为for条件的术语只是检查您是否已到达字符串的末尾。如果有,*temp将是'\0'( NUL) 和for结束。

Now, inside the for, you want to find the bits that compose *temp. Let's say we print the bits:

现在,在 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");
}

To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7to bit_index = sizeof(*temp)*8-1

为了使它更通用一点,即将任何类型转换为位,您可以更改bit_index = 7bit_index = sizeof(*temp)*8-1

回答by Simlandir

unsigned char c;

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

printf("\n");

Explanation:

解释:

With every iteration, the most significant bit is being read from the byte by shifting it and binary comparing with 1.

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

For example, let's assume that input value is 128, what binary translates to 1000 0000. Shifting it by 7 will give 0000 0001, so it concludes that the most significant bit was 1. 0000 0001 & 1 = 1. That's the first bit to print in the console. Next iterations will result in 0 ... 0.

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