How do you convert a struct into a char array?

15,249

First you need to copy the data of the struct into a byte array

int len = sizeof(struct sMSG);
unsigned char * raw = malloc(len);
memcpy(raw, &msg, len);

Now use a function to convert the byte array into Base64 text or just hexadecimal representation (2 chars/byte). Since you use the embedded tag, the latter might be the easiest to implement.

#define TOHEX(x) (x > 9 ? (x - 10 + 'A') : (x + '0'));
char * text = malloc(2 * len + 1);
for (int i = 0; i < len; i++)
{
    text[2 * i + 0] = TOHEX(raw[i] >> 4);
    text[2 * i + 1] = TOHEX(raw[i] & 0xF);
}
text[2 * len] = '\0';

free(raw);
free(text);
Share:
15,249
Admin
Author by

Admin

Updated on July 27, 2022

Comments

  • Admin
    Admin over 1 year

    I am a little bit confused on how to convert a struct to a char[] in C.

    My CDMA modem doesn't support sending variables - it only understands ASCII characters. I need to do the conversion operation.

    Let's say that I have an sMSG struct like this:

    struct sMSG
    {
        int a;
        int b[];
        char c[];
        double d;
        float f;
    };
    

    So, I have to make a string like char str[] = "sMSG_converted_into_ASCII_chars";

    I'm wondering if somebody will help me out on this, please.

    Thanks in advance.

  • Shahbaz
    Shahbaz about 12 years
    I was gonna say sprintf it into a large enough array, but this solution is better! The sprintf solution has a problem handling field separators.
  • moooeeeep
    moooeeeep about 12 years
    will the data those arrays point to be copied using memcpy this way (or will rather the pointers be copied)?
  • ArjunShankar
    ArjunShankar about 12 years
    whether this 'just works' really depends on who 'sends' messages to whom, what the sizes of different data types are, endian-ness, etc etc. You can't just read this on a different machine and 'memcpy' it back into the right structure.
  • huysentruitw
    huysentruitw about 12 years
    @ArjunShankar: that's correct, especially floats and double could even raise more trouble (if both platforms use a different notation)
  • uɐɪ
    uɐɪ about 12 years
    This assumes (BIG ASSUMPTION) that there are no empty bytes in the data structure that you are memcpy'ing. If the data elements are not assigned to a single contiguous set of memory locations then you will have extra padding bytes in the transmitted data. The values in these locations are undefined and could have undesirable effects.