Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly convert an unsigned char array into an uint32_t

Tags:

c

casting

So, I'm trying to convert an array of unsigned chars into an uint32_t, but keep getting different results each time:

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

Now, I keep getting this warning:

warning: initialization makes integer from pointer without a cast

When I change num to *num i don't get that warning, but that's not actually the real problem (UPDATE: well, those might be related now that I think of it.), because every time I run the code there is different results. Secondly the num, once it's cast properly, should be 128, but If I need to change the endianness of the buffer I could manage to do that myself, I think.

Thanks!

like image 309
omninonsense Avatar asked Aug 14 '11 19:08

omninonsense


People also ask

Can you cast unsigned char to char?

However, from i=128:255 the chars and the unsigned chars cannot be casted, or you would have different outputs, because unsigned char saves the values from [0:256] and char saves the values in the interval [-128:127]).

What is unsigned char array?

unsigned char is a character datatype where the variable consumes all the 8 bits of the memory and there is no sign bit (which is there in signed char). So it means that the range of unsigned char data type ranges from 0 to 255.

What is UInt32 in C?

In C#, UInt32 struct is used to represent 32-bit unsigned integers(also termed as uint data type) starting from range 0 to 4,294,967,295.


2 Answers

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.

like image 119
cnicutar Avatar answered Sep 18 '22 17:09

cnicutar


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.

like image 44
R.. GitHub STOP HELPING ICE Avatar answered Sep 17 '22 17:09

R.. GitHub STOP HELPING ICE