开发者

Extract 2bytes (u_short) from pointer

开发者 https://www.devze.com 2023-03-08 16:14 出处:网络
I have a pointer and I want to assign the bytes from x to (x+1) to a unsigned short. I was hoping that I could just

I have a pointer and I want to assign the bytes from x to (x+1) to a unsigned short. I was hoping that I could just

(unsigned short) po开发者_开发百科inter[x]

but the first byte seems to always be empty. But when I check the value of bytes x and x+1 individually the data is there.

Where have I noobed? (I just made it a verb)


unsigned short i = (pointer[x] << 8) + pointer[x+1]

Assuming you want x to be the high bits and x+1 to be the low bits. Actually, you should keep endianness in mind here too.

EDIT:

This may also work:

*(unsigned short *) pointer[x]

However, this will be affected by endianness, for example, in little endian the first byte will be the lower 8 bits, while x+1 will be the higher bytes.

0

精彩评论

暂无评论...
验证码 换一张
取 消