简体   繁体   English

C-将char显示为十六进制

[英]C - display char as hex

I want to print the ASCII code of a char in hex; 我想以十六进制打印字符的ASCII码; for example, for 例如,对于

char a = 0xA5;

I want to print A5 on the console. 我想在控制台上打印A5 Here is what I have tried: 这是我尝试过的:

char a = 0xA5;
printf("%02X", a);

but i get FFFFFFA5 . 但是我得到了FFFFFFA5 How could I solve this? 我该如何解决?

Cast the value to unsigned char , then cast again to unsigned int to be printed via %X . 将值强制转换为unsigned char ,然后再次强制转换为unsigned int ,以通过%X打印。

char a = 0xA5;
printf("%02X", (unsigned int)(unsigned char)a);

Note that conversion to signed integer which is not capable to store original value is implementation-defined, but conversion to unsigned integer is defined, according to N1256 6.3.1.3 请注意,根据N1256 6.3.1.3,转换为不能存储原始值的有符号整数是由实现定义的,但已定义为无符号整数的转换

The "problem" is called sign extension -- parameteres are passed as int by default so a char would be converted to int and in the process the sign extension would means that the extra f are added -- make the char unsigned like this “问题”称为符号扩展-默认情况下,参数作为int传递,因此char将被转换为int,在此过程中,符号扩展将意味着添加了额外的f-使char像这样无符号

unsigned char a = 0xA5;
printf("%02X", a);

and the compiler will understand how to treat your data. 编译器将了解如何处理您的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM