How to properly convert an unsigned char array into an uint32_t

First, you want to say num = *(uint32_t *)&buffer

To change endianness, you can use a call like bswap_32 (in linux, byteswap.h) or OSSwapInt64 (in osx, libkern/OSByteOrder.h)


cnicutar's answer is the best assuming you want a particular fixed endianness. If you want host endian, try:

uint32_t num;
memcpy(&num, buffer, 4);

or apply ntohl to cnicutar's answer. Any method based on type punning is wrong and dangerous.


The warning was issued because &buffer yields a pointer to pointer. Even without the reference operator & the warning wouldn't have disappeared because the casting changes only the pointer type. The pointer is further converted to integer and therefore the warning.

If endianness is not important, the obvious solution seems to me

unsigned char buffer[] = {0x80, 0x00, 0x00, 0x00};
uint32_t num = *(uint32_t *)buffer;

which means dereferencing the casted pointer to the char array.


Did you try this ?

num = (uint32_t)buffer[0] << 24 |
      (uint32_t)buffer[1] << 16 |
      (uint32_t)buffer[2] << 8  |
      (uint32_t)buffer[3];

This way you control endianness and whatnot.

It's really not safe to cast a char pointer and interpret it as anything bigger. Some machines expect pointers to integers to be aligned.

Tags:

C

Casting