Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit typecasting in C (Converting 32 bit unsigned in to 8 bit u int)

Tags:

c

casting

My question looks a lot like

How to store a 64 bit integer in two 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?

like image 957
Peter Avatar asked Jun 28 '10 14:06

Peter


1 Answers

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.

like image 150
Nikolai Fetissov Avatar answered Nov 15 '22 19:11

Nikolai Fetissov