On Jun 24, 4:13 pm, John Harrison <john_androni...@hotmail.comwrote:
Quote:
Bartholomew Simpson wrote:
Quote:
I need to pack two small values into a double data type.
Quote:
Quote:
I have come up with the following struct, which only takes up 16 bits
and can therefore be stored safely in a double.
Quote:
Quote:
struct mytype_
{
unsigned char fld1: 4,
fld2: 12;
};
Not sure I understand this. On most machines, the maximum size
of a character bit field will be 8.
Quote:
Quote:
My question though is how do I assign a value of type mytype to a double
(and back from a double)?
Quote:
Quote:
struct mytype_ snoopy ;
double foobar ;
Quote:
Quote:
snoopy.fld1 = 2;
snoopy.fld2 = 256 ;
Quote:
Quote:
//Are these legal (i.e. will they behave as expected - display value
semantics behaviour)?
foobar = snoopy ;
snoopy = foobar ;
Quote:
Your code is not legal (no surprise). I guess the only way to do this is
to use a union
Quote:
struct mytype_
{
unsigned char fld1:4, fld2:12;
};
Quote:
union wierd
{
double d;
mytype m;
};
Quote:
snoopy.fld1 = 2;
snoopy.fld2 = 256;
wierd foobar;
foobar.m = snoopy;
snoopy = foobar.m;
Quote:
Use foobar.d to get the double value.
Use foobar.d and get undefined behavior, you mean.
The only way to legally do what he wants is to find an
expression which uniquely specifies the two values, and will
always result in a value which is exactly representable in a
double. Since his code suggests that the values are in the
range 0...15 and 0...4095, something like:
double d = 16.0 * fld2 + fld1 ;
would do the trick, with:
int fld1 = (int)d % 16 ;
int fld2 = (int)( d / 16 ) ;
to read them.
Quote:
Although what value it will be is anyone's guess.
A signaling NaN?
--
James Kanze (Gabi Software) email:
james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34