Question

I am having some trouble casting uint8 and uin32 in embedded C. Here is the code I am using...

int b = 0;
u8 dt[4] = {0};
while (there_is_buffer(rbuf)) {
    dt[b] = (u8)(popFront(rbuf));
    if (b > 2) {
        uint32_t _Recv = (uint32_t)dt;

        /*      xil_printf("data: %x%x%x%x\n\r",dt[3], dt[2], dt[1], dt[0]);  */
        xil_printf("data: %x\n\r", _Recv);
        b = 0;
    }
    else  
        b++;
}

The printf statement that is commented out works fine, but the other one doesn't. What am I doing wrong in here? How can I cast the u8 array to uint32?

Was it helpful?

Solution

That's because dt is a pointer so when you cast it to uint32_t you just take its address as the value that will be stored in _Recv.

You should try casting it to a uint32_t and then dereference it:

uint32_t _Recv = *((uint32_t*)dt)

so that the address will be interpreted as a pointer to an unsigned int.

A more readable approach would be to build the value with shifts:

uint32_t _Recv = dt[3]<<24 | dt[2]<<16 | dt[1]<<8 | dt[0];

This will also allow you to manage endianness as you wish.

OTHER TIPS

There is another way using memcpy and is machine independent.

memcpy (&_Recv,&dt[0],4);
_Recv=htons(_Recv);

This way you can have an array of uint8 and cast any 4 bytes to uint32

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top