我正在尝试将gps坐标打包并解包到字符缓冲区中:
我有一个这样的gpscoords结构:

typedef struct {
    char north;
    uint16_t lat;
    uint16_t lat_frac;
    char east;
    uint16_t lon;
    uint16_t lon_frac;
} gpscoords;

如何将gpscoords打包并解压到buffer变量指向的缓冲区中?我想在打包前把整数转换成网络顺序,但我在下面做得不对:
void pack_gpscoords(gpscoords *pos, char *buffer) {
    pack_gpscoords(pos, &buffer);
    memcpy(buffer, pos, sizeof(pos)+1);
}

void unpack_gpscoords(gpscoords *pos, char *buffer) {
    unpack_gpscoords(pos, &buffer);
    memcpy(pos, buffer, sizeof(buffer)+1);
}

最佳答案

您应该将字节缓冲区设置为unsigned char,而不是char
你可以这样做:

void pack_gpscoords(gpscoords *pos, unsigned char *buffer) {
    buffer[0] = pos->north;
    buffer[1] = pos->lat >> 8;
    buffer[2] = pos->lat & 255;
    buffer[3] = pps->lat_frac >> 8;
    buffer[4] = pps->lat_frac & 255;
    buffer[5] = pos->east;
    buffer[6] = pos->lon >> 8;
    buffer[7] = pos->lon & 255;
    buffer[8] = pps->lon_frac >> 8;
    buffer[9] = pps->lon_frac & 255;
}

void unpack_gpscoords(gpscoords *pos, const unsigned char *buffer) {
    pos->north = buffer[0];
    pos->lat = (buffer[1] << 8) | buffer[2];
    pos->lat_frac = (buffer[3] << 8) | buffer[4];
    pos->east = buffer[5];
    pos->lon = (buffer[6] << 8) | buffer[7];
    pos->lon_frac = (buffer[8] << 8) | buffer[9];
}

笔记:
面向字节的压缩表示采用相同的字段顺序。
网络顺序表示大端:第一个字节包含高位8位,第二个字节包含低位8位。

关于c - C:如何将结构打包和解包到char缓冲区中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36104244/

10-11 23:16