2

我对如何在 C 中将 struct 转换为 char[] 有点困惑。

我的 CDMA 调制解调器不支持发送变量——它只能理解 ASCII 字符。我需要进行转换操作。

假设我有一个这样的 sMSG 结构:

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

所以,我必须制作一个像char str[] = "sMSG_converted_into_ASCII_chars";

我想知道是否有人会帮助我解决这个问题,拜托。

提前致谢。

4

1 回答 1

5

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);
于 2012-04-03T09:21:29.490 回答