char *buffer;
short num;
memcpy(&num, buffer, sizeof(short));
*buffer
- 指向缓冲区的指针,其中数字位于十六进制 View 中。
我想把这个数字放在变量 num
中而不调用 memcpy
。
我该怎么做?
number = (short) buffer; //DOESN'T work!
最佳答案
目前所有答案都建议使用*(short *)buf
,但这没有任何好处——它打破了严格的别名规则(short
的对齐方式大于char
,所以你不能在不调用未定义行为的情况下执行此操作)。
简短的回答是:你最好使用 memcpy()
,但如果你真的不想那样,那么你可以使用 union 和“类型双关”(请注意,这可能会导致字节缓冲区的陷阱表示,这可能是您想要的,也可能不是您想要的):
union type_pun {
char buf[sizeof(short)];
short s;
};
union type_pun tp;
tp.buf[0] = 0xff;
tp.buf[1] = 0xaa; // whatever, if `short' is two bytes long
printf("%hd\n", tp.s);
关于将 char 转换为 short,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16851340/