将C字符串转换为二进制表示形式 [英] Converting C string to binary representation
问题描述
在ANSI C中,如何将字符串转换为二进制字节数组? 所有的谷歌搜索和搜索都为我提供了C ++和其他(而不是C)的答案.
In ANSI C, how do we convert a string in to an array of binary bytes? All the googling and searching gives me answers for C++ and others and not C.
我的一个想法是将字符串转换为ASCII,然后将每个ASCII值转换为其二进制. (Du!)我知道这是最愚蠢的想法,但是我不确定其他任何选择.
One idea I had was to convert the string into ASCII and then convert each ASCII value into its binary. (Duh!) I know it is the dumbest of ideas but I am not sure of any other option.
我听说过Java中的编码功能.我不确定这是否适合相同的目的,并且可以被C采纳.
I've heard abt the encoding function in Java. I am not sure if that suits the same purpose and can be adopted to C.
string = "Hello"
bytearr[] = 10100101... some byte array..
如果有人可以对此有所启发,那就太好了.
It would be great if someone can throw some light on this.
谢谢!
推荐答案
还是您的意思是如何将C字符串转换为二进制表示形式?
Or did you mean how to convert C string to binary representation?
这里是一种可以将字符串转换为二进制表示的解决方案.可以很容易地对其进行更改,以将二进制字符串保存到字符串数组中.
Here is one solution which can convert strings to binary representation. It can be easily altered to save the binary strings into array of strings.
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argv[1] == NULL) return 0; /* no input string */
char *ptr = argv[1];
int i;
for(; *ptr != 0; ++ptr)
{
printf("%c => ", *ptr);
/* perform bitwise AND for every bit of the character */
for(i = 7; i >= 0; --i)
(*ptr & 1 << i) ? putchar('1') : putchar('0');
putchar('\n');
}
return 0;
}
示例输入&输出:
Example input & output:
./ascii2bin hello
h => 01101000
e => 01100101
l => 01101100
l => 01101100
o => 01101111
这篇关于将C字符串转换为二进制表示形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!