user1517372
user1517372

Reputation: 21

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):

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.

Thanks

Upvotes: 2

Views: 6000

Answers (3)

Mihai Maruseac
Mihai Maruseac

Reputation: 21460

It does this because the first bit of the char you're printing is 1, thus the char is interpreted as a negative number. 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). Thus, the sign gets copied to all other positions, making you see those fs in the output.

One fix would be to print using %hhx (you're telling printf that you're printing unsigned char values).

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

Another fix will be to change the type of the string_ptr to be unsigned char

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

Or, you can combine them.

Upvotes: 1

Specksynder
Specksynder

Reputation: 843

Use the width option in printf format specifier to print as many characters of the address as you would prefer. For instance, here you could use %2X as your format specifier.

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

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.

Try this:

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

Upvotes: 0

Related Questions