View previous topic :: View next topic |
Author |
Message |
BOB_SANTANA
Joined: 16 Oct 2006 Posts: 110 Location: HOVE, EAST SUSSEX
|
Combine the 4 nibble to form 16bits |
Posted: Sat Dec 02, 2006 9:19 am |
|
|
Just thought i asked this
Is there a better way of getting a 16bit variable from 4 different
8bit variables
This assumes that i only need the lower bits from the variables result[0]-result[3]
Code: |
update = (( result[0]* 4096) + (result[1]*256) + (result[2] * 16) + (result[3]));
// Combine the 4 lower bits of result[0]-result[3]to form a 16bit variable
|
_________________ BOB_Santana |
|
|
Ttelmah Guest
|
|
Posted: Sat Dec 02, 2006 10:42 am |
|
|
Code: |
struct nibbles {
int8 n[4]:4;
};
union {
struct nibbles bit4;
int16 word;
} access;
|
access.bit4.n[0] to access.bit4.n[3] are the four nibbles, and access.word is then the 16bit value.
You don't even need the seperate array.
Best Wishes |
|
|
ferrumvir
Joined: 01 Feb 2006 Posts: 64 Location: England
|
|
Posted: Sat Dec 02, 2006 2:43 pm |
|
|
Ttelmah,
I like your solution, atually it's the first time I've actually understood the use/power of union.
But I have an alternative,
BOB_SANATA.
It really depends upon what else you are doing with the data - If it's a one off conversion then the following may be more computationally efficient (though I could wrong)
Code: | // DECLARATIONS
int16 update;
int8 r[4]; // ONLY SET/USE 4 BITS
// CONVERSION
update = ((int16)r[0]<<12) + ((int16)r[1]<<8) + (r[2]<<4) + (r[3]);
|
If you want to concentrate more on the using the two inter-changably and therefore greatly simplifing the C code then I'd go with Ttelmah.
Cheers Scott |
|
|
BOB_SANTANA
Joined: 16 Oct 2006 Posts: 110 Location: HOVE, EAST SUSSEX
|
|
Posted: Sat Dec 02, 2006 2:55 pm |
|
|
Thanks guys
As a newby to C i didn't understand the way unions & structure works
so i had to go back to basics
I am reading about them now
I want to be a c programmer like you guys
As for what i am doing with the Data , i am passing it to a function that
updates a set a 16 relays _________________ BOB_Santana |
|
|
|