简体   繁体   English

以十六进制打印数据结构值

[英]printing of a Data struct values in hex

typedef struct AbcStruct{

   short        LD;
   short        EL;
   short        CL;        
   AbcStruct( short b, short res = 0, short lr = 1000): LD( b ), EL(res), CL( lr ) { }
};

int main () 
{

    struct AbcStruct A2(200, 100, 100);

    char *string_ptr = (char *)&A2;
    kk = sizeof(AbcStruct);

    while(kk--)
        printf(" %x ", *string_ptr++);
}

Output (AbcStruct in Hex): 输出(十六进制的AbcStruct):

ffffffc8  0  64  0  64  0

I'm wondering why the output of first element contains 4 bytes: ffffffc8 when I was expecting it wouldd just print c8 . 我想知道为什么第一个元素的输出包含4个字节: ffffffc8当我期望它只会打印c8

Thanks 谢谢

It does this because the first bit of the char you're printing is 1 , thus the char is interpreted as a negative number. 这样做是因为您要打印的char的第一位是1 ,因此char被解释为负数。 When you're printing using the default %x format, the value to be printed is interpreted as being an int (much larger than the char ). 当您使用默认的%x格式进行打印时,要打印的值被解释为一个int (比char大得多)。 Thus, the sign gets copied to all other positions, making you see those f s in the output. 因此,符号被复制到所有其他位置,使您在输出中看到那些f s。

One fix would be to print using %hhx (you're telling printf that you're printing unsigned char values). 一种解决方法是使用%hhx进行打印(您告诉printf您正在打印unsigned char值)。

printf(" %hhx ", *string_ptr++);

Another fix will be to change the type of the string_ptr to be unsigned char 另一个解决方法是将string_ptr的类型更改为unsigned char

unsigned char *string_ptr = (char *)&A2;

Or, you can combine them. 或者,您可以将它们合并。

You are telling printf() to treat what is returned from the address pointed to by string_ptr as an unsigned int (which I guess is 32-bits long on your system) rather than an unsigned char . 您要告诉printf()string_ptr指向的地址返回的string_ptr视为unsigned int (我猜它在系统上为32位长),而不是unsigned char

Try this: 尝试这个:

unsigned char *string_ptr = (unsigned char *)&A2;
kk = sizeof(AbcStruct);
while(kk--)
{
    unsigned char c = *string_ptr++;
    printf(" %x ", (unsigned)c);
}

Use the width option in printf format specifier to print as many characters of the address as you would prefer. 在printf格式说明符中使用width选项可根据需要打印尽可能多的地址字符。 For instance, here you could use %2X as your format specifier. 例如,在这里您可以使用%2X作为格式说明符。

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

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