Re: Application of Union in C
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 19 Apr 2006 19:23:23 GMT
"Vladimir S. Oka" <novine@xxxxxxxxxxxxxxx> writes:
[...]
Probably the best way to explore bit-representation of `float`/`double`
is to use a `union` with a `char` array:
union
{
char b[SIZEOF_DOUBLE];
double d;
}
Where SIZEOF_DOUBLE is, obviously == `sizeof(double)`.
Reading out values of `b[index]` is always OK, as `char` cannot have
trap representation. Be careful if you want to experiment by writing to
`b[index]`, as it may create a trap representation of `d`. This will be
a problem once `d` is read (provided it assumed a trap value).
It's much better to use unsigned char rather than char (which can be
either signed or unsigned). I think you're right that char can't have
trap representations, but it can have padding bits; unsigned char
cannot.
In general, storing a value in one member of a union and then reading
another member is dangerous unless the member you read is an array of
unsigned char. Using a union to overlay the representations of two
different types is common, but it's not really supported by the
standard.
Another common use of unions is to implement something like Pascal's
variant records. For example:
enum type { INT, DOUBLE, POINTER };
struct variant {
enum type current_type;
union {
int i;
double d;
void *p;
}
}
The value of the current_type member indicates which union member is
currently active.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- Follow-Ups:
- Re: Application of Union in C
- From: Vladimir S. Oka
- Re: Application of Union in C
- References:
- Application of Union in C
- From: balasam
- Re: Application of Union in C
- From: rrs . matrix
- Re: Application of Union in C
- From: Naresh
- Re: Application of Union in C
- From: Abdo Haji-Ali
- Re: Application of Union in C
- From: Vladimir S. Oka
- Application of Union in C
- Prev by Date: Re: direction of stack growth
- Next by Date: Re: portability issues with ' flag in printf
- Previous by thread: Re: Application of Union in C
- Next by thread: Re: Application of Union in C
- Index(es):
Relevant Pages
|