<bl**********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
: int a[4]={1,2,3,4};
: but i d rather not use int (which on my machine is 4 bytes) I d like to
: store all 4 values in 4elements*4bits=16bits=2bytes.
: How do i do that?
You could try:
struct Quad4 {
unsigned a : 4; //allocate only 4 bits for this field
unsigned b : 4;
unsigned c : 4;
unsigned d : 4;
};
This is likely to do what you want on many platforms, but
implementation details and in-memory representation may vary.
Simply assigning/reading the fields of the above structure
will have the compiler pack/unpack the values for you
automatically.
Alternatively, you can manually control the packing with
something like:
unsigned pack(unsigned a, unsigned b, unsigned c, unsigned d)
{
return ((a&7)<<12)|((b&7)<<4)|((c&7)<<8)|(d&7);
}
....and store the packed value in a 16-bit unsigned
integer variable, then:
void unpack(unsigned v /*packed value*/
, unsigned& a, unsigned& b, unsigned& c, unsigned& d)
{
a = (v>>12)&7;
b = (v>> 8)&7;
c = (v>> 4)&7;
d = v &7;
}
hth --Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <>
http://www.brainbench.com