简而言之
char *buffer; short num; memcpy(&num, buffer, sizeof(short));
*buffer
– 指向*buffer
指针,其中number位于HEX视图中。 我想把这个数字放在变量num
而不调用memcpy
。 我该怎么做?
number = (short) buffer; //DOESN'T work!
对于两个字节的短:
number = (short)( ((unsigned char)buffer[0]) << 8 | ((unsigned char)buffer[1]) );
对于不同的简短:
for (int i = 0; i < sizeof(short); i++) number = (number << 8) + ((unsigned char) buffer[i]);
或者你会为每种尺寸都有一些宏。
另外,请参阅tristopia关于这种关于字节序的假设的评论。
到目前为止,所有答案都建议使用*(short *)buf
,但这没有任何好处 – 它打破了严格的别名规则( short
的对齐大于char
的对齐,所以如果不调用未定义的行为就不能这样做)。
简短的回答是:你最好使用memcpy()
,但如果你真的不想那样,那么你可以使用联合和“打字”(注意这可能会导致陷阱表示缓冲区)字节,可能是你想要的或不是你想要的):
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);
根据你的sizeof(short)
字节的memcpy,我猜你想要从缓冲区指向的第一个sizeof(short)
字节。
number = * (short *) buffer;
正如其他人所指出的那样,会为你做到这一点。
你不能把指针的地址放在一个短的地方,所以你需要取消引用它来获取内存中的值。
假设“位于HEX视图中”表示数字存储在字符串中,如“89AB”,则可以使用strtol
函数。
char* end; num = (short)strtol(buffer, &end, 16);
此函数将字符串转换为长整数。 没有相应的函数可以直接转换为short,所以你无论如何都要做(short)
,但这不是问题,是吗?