Home > other >  Converting a struct to a hex string in C
Converting a struct to a hex string in C

Time:03-10

I have the following struct

typedef struct __attribute__((packed)) word {
    uint16_t value;
    uint8_t flag
} Word;

I want to convert it to a hex string. For example if value = 0xabcd and flag = 0x01 I want to get the string 01abcd

if I do some pointer juggling

Word word;
word.value = 0xabcd;
wordk.flag = 0x01;

printf("word: %X\n", *(int *)&word);

I get the output that I want (word: 1ABCD) but this doesn't seem safe and when I tried to do this after looking at some of the answer here

char ptr[3];
memcpy(ptr, word, 3);
printf("word: XXX\n", ptr[2], ptr[1], ptr[0]);

I got word: 01FFFFFFABFFFFFFCD, for some reason the first two bytes are being extended to a full int

CodePudding user response:

Use a simple sprintf to convert to a string:

int main(void)
{
    Word v = { 0xabcd, 0x01 };
    
    char s[10];
    
    sprintf(s, "xx", v.flag, v.value);
    
    puts(s);
}

CodePudding user response:

There's no real gain from messing around with pointers or type-punning, if all you want is to output the values of the two structure members. Just print them individually:

printf("word: xx\n", (unsigned int)word.flag, (unsigned int)word.value);
  •  Tags:  
  • c
  • Related