Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 15 Aug 2012 10:47:55 +0200
From:      =?ISO-8859-1?Q?V=E1clav_Zeman?= <vhaisman@gmail.com>
To:        freebsd-hackers@freebsd.org
Subject:   Re: Unsigned Integer Encoding
Message-ID:  <502B623B.2070606@gmail.com>
In-Reply-To: <CAG167sY3-i_MimZGJ7qv9NC-u6e2w6RWq_fZt3amFn3%2BjdeKbQ@mail.gmail.com>
References:  <CAG167sY3-i_MimZGJ7qv9NC-u6e2w6RWq_fZt3amFn3%2BjdeKbQ@mail.gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help
This is an OpenPGP/MIME signed message (RFC 2440 and 3156)
--------------enig73BEA7D173F9960B8AA395F1
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

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 t=
o
> 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 =3D 0x01020304;
>
> /* This prints 01020304 */
> printf ("a =3D %0X \n",a);
>
> uint32_t * b;
>
> uint8_t bytes [] =3D {0x01,0x02,0x03,0x04};
>
> b =3D (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=3D %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 stre=
am
> 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 i=
n
> reverse form).
>
> Thanks in advance for your help.

--=20
VZ




--------------enig73BEA7D173F9960B8AA395F1
Content-Type: application/pgp-signature; name="signature.asc"
Content-Description: OpenPGP digital signature
Content-Disposition: attachment; filename="signature.asc"

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.17 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iF4EAREIAAYFAlArYjsACgkQ6OWUyaYNY6MRzgD7BdmGsUzPIYKZKFZ/QofJsLdn
L9f4HG0GC8fH9eL2U74A/2ONwGMLRWtpQs93ftDtO91x6nZoq5SPzfbxtknEUmIN
=QQ7b
-----END PGP SIGNATURE-----

--------------enig73BEA7D173F9960B8AA395F1--



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?502B623B.2070606>