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?
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.