Reputation: 159
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!
Upvotes: 4
Views: 2458
Reputation: 146910
You should use a union.
union charint32 {
char arr1[4];
uint32_t num;
};
This will simplify storage and casting for you.
Upvotes: 5
Reputation: 98736
Yes, that should work fine (under your assumption of endianness), since the representation of these bytes in memory is the same regardless of whether it's interpreted as an array of bytes or an integer.
Really all you're doing is changing the type, not the data.
Upvotes: 0
Reputation: 77722
It is technically safe, but there are a few things I would consider:
num2
is a great example of why this is important - your typo would cause undefined behavior.Upvotes: 3
Reputation: 4871
If you are sure the arrays are properly aligned, then there shouldn't be a problem (given the endianness).
In the code, however, I don't know what you're doing with arr2
, since it is 16 bits, and you are reading a 32 bit quantity from it.
Upvotes: 0
Reputation: 15872
A safer approach would be to use a macro (e.g. MAKEDWORD) to put the bytes in their proper order.
Upvotes: 0
Reputation: 263078
This should be safe:
char arr1[4] = { ... };
uint32_t num1;
memcpy(&num1, arr1, sizeof num1);
But why is arr2
only 2 bytes big? Is that a typo?
Upvotes: 1