在 C 中将字符转换为二进制 [英] Conversion of Char to Binary in C

查看:12
本文介绍了在 C 中将字符转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我知道我需要换档和AND.但是,由于某种原因,我的代码无法正常工作.

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

这就是我所拥有的.*temp 指向 C 字符串中的索引.

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

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

推荐答案

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

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

printbinchar(10) 将写入控制台

printbinchar(10) will write into the console

    1010

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

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".

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

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.

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

printbincharpad(10) 将写入控制台

printbincharpad(10) will write into the console

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

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

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

1000001
1000010
110001

这篇关于在 C 中将字符转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆