So, I'm trying to convert an array of unsigned char
s 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!
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]).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With