[英]How to convert unsigned char to binary representation
I'm trying to convert unsigned chars to their hex ASCII values but in binary form.我正在尝试将无符号字符转换为其十六进制 ASCII 值,但以二进制形式。
For example:例如:
unsigned char C to 0100 0011 (43)无符号字符 C 到 0100 0011 (43)
I can get from hex to binary the issue is getting from char to its hex value.我可以从十六进制到二进制问题是从 char 到它的十六进制值。
for (n = 0; n < 8; n++){
binary[n] = (letter >> n) & 1;}
I keep getting the wrong values because the letter is going in as its own ASCII value rather than the binary version of the hex ASCII value我不断得到错误的值,因为字母是作为它自己的 ASCII 值而不是十六进制 ASCII 值的二进制版本进入的
I think you are picking the bits one by one just fine, you just get them in reverse order compared to what you wanted.我认为您可以一点一点地挑选这些位,与您想要的相比,您只需按相反的顺序获取它们。
This works:这有效:
#include <stdio.h>
int main() {
unsigned char letter = 'C';
int binary[8];
for(int n = 0; n < 8; n++)
binary[7-n] = (letter >> n) & 1;
/* print result */
for(int n = 0; n < 8; n++)
printf("%d", binary[n]);
printf("\n");
return 0;
}
Running that gives the 01000011 that you wanted.运行它会给出你想要的 01000011。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.