Unsigned Integer Encoding

Václav Zeman vhaisman at gmail.com
Wed Aug 15 08:48:01 UTC 2012


On 08/15/2012 10:33 AM, Daniel Grech wrote:
> Hi,
>
> I have what is probably a really elementary question but I can't seem to
> figure it out. In the following snippet of code, why is it that a and b do
> not have the same value in the end ?  :
>
> #define uint32_t unsigned int
> #define uint16_t unsigned short
> #define uint8_t unsigned char
> #define uint64_t unsigned long long
>
> int main ()
> {
> uint32_t a = 0x01020304;
>
> /* This prints 01020304 */
> printf ("a = %0X \n",a);
>
> uint32_t * b;
>
> uint8_t bytes [] = {0x01,0x02,0x03,0x04};
>
> b = (uint32_t *) bytes;
You cannot do this cast. The bytes array does not have to be
sufficiently aligned and you will get SIGBUS errors on strict alignment
platforms. Use memcpy() to copy from the bytes array to b instead, that
is the only portable way to do this.

>
> /* This prints 04030201 */
This is correct for LE platforms. The least significant byte (1) is
first in the array. You need to know which order of bytes does the
protocol use for transport (LE or BE) and then have the implementation
either swap or not swap the bytes appropriately.

> printf ("b= %0X \n", *b);
> return 1;
> }
>
> Im asking this as I am currently encoding a protocol in which i receive
> data as a sequence of bytes. Casting for example 4 bytes from this stream
> leaves me with the situation in variable b, while the situation I am
> looking to accomplish is the one in A (i.e. the bytes are not encoded in
> reverse form).
>
> Thanks in advance for your help.

-- 
VZ



-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 294 bytes
Desc: OpenPGP digital signature
Url : http://lists.freebsd.org/pipermail/freebsd-hackers/attachments/20120815/00380e28/signature.pgp


More information about the freebsd-hackers mailing list