我正在尝试将字符转换为其二进制表示(即字符 -> 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--;
}
我们展示了两个函数,打印单个字符的二进制表示。
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
i = CHAR_BIT - 1
。你知道的,为了适应那些9位和11位处理器。 - Chris Lutzunsigned 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。
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
。
ptrPos
是什么意思?i
是什么意思? - Hogan