在 C 中打印十六进制字符 [英] Printing hexadecimal characters in C
问题描述
我试图读入一行字符,然后打印出这些字符的十六进制等效值.
I'm trying to read in a line of characters, then print out the hexadecimal equivalent of the characters.
例如,如果我有一个字符串 "0xc0 0xc0 abc123"
,其中前 2 个字符是 c0
十六进制,其余字符是 abc123
在 ASCII 中,那么我应该得到 p>
For example, if I have a string that is "0xc0 0xc0 abc123"
, where the first 2 characters are c0
in hex and the remaining characters are abc123
in ASCII, then I should get
c0 c0 61 62 63 31 32 33
然而,printf
使用 %x
给了我
However, printf
using %x
gives me
ffffffc0 ffffffc0 61 62 63 31 32 33
如何在没有 "ffffff"
的情况下获得我想要的输出?为什么只有 c0(和 80)有 ffffff
而其他字符没有?
How do I get the output I want without the "ffffff"
? And why is it that only c0 (and 80) has the ffffff
, but not the other characters?
推荐答案
您看到 ffffff
因为 char
已在您的系统上签名.在 C 中,诸如 printf
之类的 vararg 函数会将所有小于 int
的整数提升为 int
.由于 char
是一个整数(在您的情况下为 8 位有符号整数),您的字符将通过符号扩展提升为 int
.
You are seeing the ffffff
because char
is signed on your system. In C, vararg functions such as printf
will promote all integers smaller than int
to int
. Since char
is an integer (8-bit signed integer in your case), your chars are being promoted to int
via sign-extension.
由于 c0
和 80
有一个前导 1 位(并且作为一个 8 位整数是负数),它们被符号扩展,而其他在你的样品不要.
Since c0
and 80
have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.
char int
c0 -> ffffffc0
80 -> ffffff80
61 -> 00000061
这是一个解决方案:
char ch = 0xC0;
printf("%x", ch & 0xff);
这将屏蔽高位,只保留您想要的低 8 位.
This will mask out the upper bits and keep only the lower 8 bits that you want.
这篇关于在 C 中打印十六进制字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!