Re: union to get parts of integer

Michal Nazarewicz <[email protected]> Mon, 20 Dec 2010 15:44:48 +0100
Newsgroups org.kernel.vger.linux-c-programming
Message-ID <[email protected]>
ratheesh k <[email protected]> writes:

> typedef struct {
> char parts[4];
> } node ;
>
> int i=0x12345678
>
> ((node *)&i)->parts[0];
> ((node *)&i)->parts[1];
> ((node *)&i)->parts[2];
> ((node *)&i)->parts[3];
>
> Is there any mechanism to split into bytes using the power of union ?

The above should work (assuming of course that sizeof(int) == 4).  The
following should work as well:

((char *)&i)[0].

However, are you sure that you need this?  Don't you need "(i & 255)",
"((i >> 8) & 255)", etc. instead?

-- 
Best regards,                                         _     _
 .o. | Liege of Serenly Enlightened Majesty of      o' \,=./ `o
 ..o | Computer Science,  Michal "mina86" Nazarewicz   (o o)
 ooo +--<mina86-tlen.pl>--<jid:mina86-jabber.org>--ooO--(_)--Ooo--
signature.asc (application/pgp-signature, 197 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.14 (GNU/Linux)

iEYEARECAAYFAk0Pa+UACgkQUyzLALfG3x4gSQCgigTfNVLK+BRVoJ7atWT12Q2J
4LwAmwbwmIOOJVqWiTVh2zGpqczjar08
=0kjH
-----END PGP SIGNATURE-----