how to place two unsigned 16 bit values into a 32 bit unsigned value

P

pasamdivya

Hi everyone,

I need to store an unsigned 16 bit number in the upper (MSB) and
another unsigned 16 bit number in the 16 LSB. Basically, I am trying
to store two unsigned 16 bit numbers into one unsigned 32 bit number.

So far, I have the following:

struct
{
unsigned int num1:16;
unsigned in num2:16;
} twoUnsigned16BitNums;

unsigned int num;

What I am having trouble with is to store the two 16 bit numbers into
the 32 bit number. I know one option is to use bit wise ANDs and ORs.
Any help on your part is greatly appreciated. Best Regards.
 
J

James Kanze

I need to store an unsigned 16 bit number in the upper (MSB)
and another unsigned 16 bit number in the 16 LSB. Basically, I
am trying to store two unsigned 16 bit numbers into one
unsigned 32 bit number.
So far, I have the following:
struct
{
   unsigned int num1:16;
   unsigned in num2:16;
} twoUnsigned16BitNums;

That may or may work (then memcpy'ing the results); check your
compilers documentation.
unsigned int num;
What I am having trouble with is to store the two 16 bit
numbers into the 32 bit number. I know one option is to use
bit wise ANDs and ORs.

That's the usual solution.
Any help on your part is greatly appreciated.

Is "number1 << 16 | number2" what you're looking for? (Just
make sure that 32 bit arithmetic is used here. If number1 is an
unsigned int, and int's are only 16 bits, you'll have to cast it
to unsigned long first.)
 
B

Bill Davy

Depending on portability (compiler, processor, packing, etc) you may be able
to use a union. For VS on Intel

union

{

struct

{

unsigned a:16;

unsigned b:16;

} Half;

struct

{

unsigned ab:32;

} Whole;

} t;

t.Half.a = 0x1234;

t.Half.b = 0x5678;

t.Whole.ab is now 0x56781234
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top