Re: How to extract bytes from a long?
From: Joe Wright (joewwright_at_earthlink.net)
Date: 10/16/03
- Next message: Rick: "functions returning *char"
- Previous message: Christopher Benson-Manica: "Re: bugs in c"
- In reply to: cody: "Re: How to extract bytes from a long?"
- Next in thread: Irrwahn Grausewitz: "Re: How to extract bytes from a long?"
- Reply: Irrwahn Grausewitz: "Re: How to extract bytes from a long?"
- Reply: CBFalconer: "Re: How to extract bytes from a long?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Thu, 16 Oct 2003 13:57:37 GMT
cody wrote:
>
> > > #include <stdio.h>
> > > union _x
> > > {
> > > long lng;
> > > char byt[sizeof long];
> > > }
> > >
> > > better?
> >
> > Marginally. It still doesn't address the issue raised
> > by both David Rubin and Martin Ambuhl, and it still uses
> > an identifier reserved for the implementation,
>
> What reserved identifier? Do you mean the underscore before x?
>
> > and it still
> > risks trouble with trap representations or if the system
> > uses signed magnitude or ones' complement arithmetic ...
>
> He just wanted to extract the bytes of a long. Sometimes you do not care how
> the
> bytes are represented are in that long, just getting them is enough.
>
> You should not assign new values to byt, that could cause trap
> representations as you said, but reading is allowed and safe.
>
> > ... but other than that, Mrs. Lincoln, how did you
> > like the play?
>
> What do you mean with that?
>
Cody,
They might be picking on you now. I'll move tentatively to your side.
This snippet fixes your remaining syntax error (you'll see it easily)
but provides fodder for our detractors.
I contend, as you seem to, that accessing u.lng as components of u.byt[]
is what unions are all about. We could be wrong.
Accessing memory through (unsigned char *) seems to be guaranteed to
work. I demonstrate both methods below. I don't understand why the first
is wrong while the second is right. Duck! :-)
#include <stdio.h>
typedef unsigned long ulong;
typedef unsigned char uchar;
union {
ulong lng;
uchar byt[ sizeof (ulong) ];
} u;
int main(void) {
int i, j = sizeof (ulong);
uchar *ucr = (uchar *)&u.lng;
u.lng = 0x12345678;
for (i = 0; i < j; ++i)
printf(" 0x%02X", u.byt[i]);
puts("");
for (i = 0; i < j; ++i)
printf(" 0x%02X", ucr[i]);
return 0;
}
-- Joe Wright http://www.jw-wright.com "Everything should be made as simple as possible, but not simpler." --- Albert Einstein ---
- Next message: Rick: "functions returning *char"
- Previous message: Christopher Benson-Manica: "Re: bugs in c"
- In reply to: cody: "Re: How to extract bytes from a long?"
- Next in thread: Irrwahn Grausewitz: "Re: How to extract bytes from a long?"
- Reply: Irrwahn Grausewitz: "Re: How to extract bytes from a long?"
- Reply: CBFalconer: "Re: How to extract bytes from a long?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]