在C中将字符转换为二进制
我试图将一个字符转换为它的二进制表示(所以字符 – > ascii hex – >二进制)。
我知道这样做我需要转移和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--; }
我们展示了两个将SINGLE字符打印成二进制的函数。
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,输出,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
作为条件只是检查您是否已到达字符串的末尾。 如果你有, *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");
说明:
每次迭代时,通过移位和二进制比较,从字节读取最高有效位。
例如,假设输入值为128,二进制转换为1000 0000.将其移动7将给出0000 0001,因此它得出结论:最高有效位为1. 0000 0001&1 = 1.这是第一位在控制台中打印。 下一次迭代将导致0 … 0。