dar*_*sky 7 c string binary ascii char
我试图将一个字符转换为它的二进制表示(所以字符 - > 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--;
}
Run Code Online (Sandbox Code Playgroud)
Sal*_*iti 29
我们展示了两个将SINGLE字符打印成二进制的函数.
void printbinchar(char character)
{
char output[9];
itoa(character, output, 2);
printf("%s\n", output);
}
Run Code Online (Sandbox Code Playgroud)
printbinchar(10)将写入控制台
1010
Run Code Online (Sandbox Code Playgroud)
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');
}
Run Code Online (Sandbox Code Playgroud)
printbincharpad(10)将写入控制台
00001010
Run Code Online (Sandbox Code Playgroud)
现在我提出了一个打印出整个字符串的函数(没有最后一个空字符).
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;
}
}
Run Code Online (Sandbox Code Playgroud)
但请考虑itoa不添加填充零,因此printstringasbinary("AB1")将打印如下内容:
1000001
1000010
110001
Run Code Online (Sandbox Code Playgroud)
unsigned char c;
for( int i = 7; i >= 0; i-- ) {
printf( "%d", ( c >> i ) & 1 ? 1 : 0 );
}
printf("\n");
Run Code Online (Sandbox Code Playgroud)
解释:
在每次迭代中,通过移位并与 1 进行二进制比较来从字节中读取最高有效位。
例如,假设输入值为 128,二进制转换为 1000 0000。将其移位 7 将得到 0000 0001,因此得出结论,最高有效位为 1。0000 0001 & 1 = 1。这是要转换的第一位。在控制台中打印。下一次迭代将得到 0 ... 0。
| 归档时间: |
|
| 查看次数: |
88814 次 |
| 最近记录: |