memcpy unsigned char to int



我正在尝试从我读取的文件中获取一个整数值。诀窍是我不知道这个值有多少字节,所以我首先读取长度八位字节,然后尝试读取长度八位字节告诉我的尽可能多的数据字节。当我尝试将数据八位字节放入 int 变量中并最终打印它时,问题就来了 - 如果第一个数据八位字节为 0,则只复制后面的那个,所以我尝试读取的 int 是错误的,因为0x00A2与0xA200不同。如果我使用 ntohs 或 ntohl,那么0xA200被解码为错误0x00A2,因此它不能解决孔问题。我像这样使用memcpy:

memcpy(&dst, (const *)src, bytes2read)   

其中 DST 是 int,src 是无符号字符 *,bytes2read 是size_t。

那我做错了什么呢?谢谢!

不能使用 memcpy 在整数中可移植地存储字节,因为标准未指定字节顺序,更不用说可能的填充位了。可移植的方法是使用按位运算和移位:

unsigned char b, len;
unsigned int val = 0;
fdin >> len;             // read the field len
if (len > sizeof(val)) { // ensure it will fit into an
    // process error: cannot fit in an int variable
    ...
}
while (len-- > 0) {      // store and shift one byte at a bite
    val <<= 8;           // shift previous value to leave room for new byte
    fdin >> b;           // read it
    val |= b;            // and store..
}

最新更新