copying 2 8 bit values into 1 16 bit value

Oct 2, 2008 at 7:24pm
Hey guys,
here's what I am looking to do.
Have an array thats 8 bit.
char [32].

I have a qty, say temp which is 16 bit.

I need qty to hold char [0] in first 8 bits and char[1] in next 8 bits.
Memset is givin me weird errors, so was hoping someone here could show me howto approach this or give me sample memset code.
Thanks for the help.
Oct 2, 2008 at 7:56pm
So why not

1
2
3
4
// assume
uint16_t qty;
char array[ /*some number >= 2 */ ];
qty = *static_cast<uint16_t*>( array );
Oct 2, 2008 at 8:20pm
Depending on your matter you can just define the address of your 16bit variable as the start of your 8 bit array and you will be able to change it by using both variables without to copy the hole thing.
Oct 2, 2008 at 8:56pm
Those solutions will only work on little-endian machines.

When playing with bits you should generally just give-in and do some bit-shifting.
1
2
3
4
5
char eights[ 2 ] = { 0xA2, 0x4F };  /* 0x4FA2 */

short temp = eights[ 0 ] +(eights[ 1 ] << 8);

printf( "%X\n", temp );  /* 4FA2 */

Then when your hardware changes you'll never have to wonder where your code broke.

Hope this helps.
Oct 2, 2008 at 9:09pm
@jsmith
Didnt know about the static_cast operator. Did'nt want to use typecasting as it simply converts the whole var to the typecasted qty.
What i did was cast a struct, typecasted the array to this struc and that way I got my 16 bit structure.
Thanks @jsmith,Duoas and JMC too.
Topic archived. No new replies allowed.