在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,那么我应该得到
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
,因为字符
您的系统上签字。在C语言中,可变参数的功能,如的printf
将推动比 INT
较小的所有整数 INT
。由于字符
是一个整数(在您的案件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屋!