Allocating an array of characters into an integer

EDIT: fixed wrong type num2.

Hello,

I have several arrays of characters of a known size that contains raw integer data read from a binary file.

The size of all these arrays is the size of integers.

I would like to ask if the following operation is safe and accurate under ALL normal conditions, assuming that the correspondence between the source data and the computer running this code is consistent.

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!

+3
source share
6 answers

This is technically safe, but there are a few things I would think:

  • , . , char sizeof (your_int_type)? num2 - , - undefined.
  • . , char 4- ( int 4 )? PowerPC, , , int .
+3

.

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

.

+5

:

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

uint32_t num1;

memcpy(&num1, arr1, sizeof num1);

arr2 2 ? ?

+1

(, MAKEDWORD), .

0

, , ( ).

In the code, however, I do not know what you are doing with arr2, since it is 16 bits and you are reading a 32-bit amount from it.

0
source

Yes, this should work fine (according to your assumption about the content), since the representation of these bytes in memory is the same regardless of whether it is interpreted as an array of bytes or an integer.

In fact, all you do is change the type, not the data.

0
source

Source: https://habr.com/ru/post/1779034/


All Articles