On 08/01/2011 09:09 AM, David Laight wrote:
If you have 'unsigned char bloc[]' and want to read a 32 bit LE value you can do: value = bloc[20 + 0]; value |= bloc[20 + 1]<< 8; value |= bloc[20 + 2]<< 16; value |= bloc[20 + 3]<< 24; *offs = value; And that is correct on all architectures.
I have a BYTE[] so I will do that. I was worried about compatibility across architectures but as you pointed out, my code is slow and even wrong. As always, KISS !
To write a LE value use: buf[0] = value; buf[1] = value>>= 8; buf[2] = value>>= 8; buf[3] = value>>= 8;
(For BE reverse the indexes)
Thanks for remembering me this compact syntax.
If the item is known to be correctly aligned (or the architecture supports mis-aligned reads) then you can just do (eg): value = *(uint32_t *)(bloc + 20); value = le32toh(value); but you'll have to chase around the OS headers to find how to spell le32toh().
If I had something like uint128_t (I doubt it will ever exist), then yeah, I would try to avoid 32 lines of code and bit shifting but I prefer the above solution in my case.
If you define a C struct that matches the data area (packed if it might
I thought about it but I only use the value once.
Thanks for all your advices. Will "star" this e-mail if I need it later.
David