tags:

views:

203

answers:

4

My question looks a lot like

http://stackoverflow.com/questions/2810280/how-to-store-a-64-bit-integer-in-2-32-bit-integers-and-convert-back-again

(I have an unsigned 32 bit I need to put into 4 unsigned 8-bit variables in C)

but

My question is whether this:

uint8_t a;
uint32_t b;
a = b;

guarantees that a is filled with the eight rightmost bits, rather than the eight leftmost bits?

+5  A: 

I don’t know what you mean by rightmost and leftmost (endianness?) but C guarantees that a will contain the 8 lower-order (least significant) bits of b. That is, the assignment will be logically equivalent to:

a = b % ((uint32_t)UINT8_MAX + 1);
Konrad Rudolph
+2  A: 

Yes. Do either this:

uint32_t num32 = 0xdeadbeef;

uint8_t a = num32;       /* 0xef */
uint8_t b = num32 >> 8;  /* 0xbe */
uint8_t c = num32 >> 16; /* 0xad */
uint8_t d = num32 >> 24; /* 0xde */

Or this:

union u
{
    uint32_t num32;

    struct
    {
        uint8_t a;
        uint8_t b;
        uint8_t c;
        uint8_t d;

    } bytes;

} converter;

converter.num32 = 0xdeadbeef;

The first example does not depend on platform endianess, the second does.

Nikolai N Fetissov
While your first method should work on all compilers and platforms, the second method is limited to platform in little endian format.
Tom
Yes, that's what I said in the answer, didn't I?
Nikolai N Fetissov
A: 

You might look at the union declaration. If you can guarantee the processor/source of data won't change I think you can assume 'endianness'

Jay
+1  A: 
KennyTM