Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a character array into an integer

EDIT: The wrong type of num2 has been corrected.

Hello,

I have some character arrays of known size which contains raw integer data read from a binary file.

The size of all these arrays have the size of a integer.

I would like to ask whether the following operation is safe and accurate in ALL normal situation, assuming that the endianness of the raw data and the computer running this code agrees.

char arr1[4] = { ... };
char arr2[2] = { ... };

uint32_t num1 = *static_cast<uint32_t*>(arr1); /* OR num1 = *(uint32_t*)arr1 in C */
uint16_t num2 = *static_cast<uint16_t*>(arr2); /* OR num2 = *(uint32_t*)arr2 in C */

Thank you!

like image 956
Ron Lau Avatar asked Nov 15 '25 08:11

Ron Lau


2 Answers

You should use a union.

union charint32 {
    char arr1[4];
    uint32_t num;
};

This will simplify storage and casting for you.

like image 172
Puppy Avatar answered Nov 17 '25 20:11

Puppy


It is technically safe, but there are a few things I would consider:

  • Add compile-time asserts to verify the sizes. Are you SURE that your char array equals sizeof(your_int_type)? Your num2 is a great example of why this is important - your typo would cause undefined behavior.
  • Consider the alignment. Are you sure that your char array is on a 4-byte boundary (assuming your int is 4 bytes)? PowerPC for example will crash if you try to read an int from an unaligned pointer.
like image 45
EboMike Avatar answered Nov 17 '25 20:11

EboMike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!