If I understand what you are doing, then yes, you can access both bytes by casting to uint16_t
, but you will run into problems (or endianess issues) with how the order the bytes are stored in memory as well as violate strict-aliasing. This will probably return an answer you were not suspecting. For example:
#include <stdio.h>
#include <stdint.h>
int main (void) {
uint8_t array[] = {1,2,3,4};
uint8_t *p = array + 2;
printf ("\n the uint8_t answer : %hhd\n", *p);
printf (" the uint16_t answer : %hd\n\n", *(uint16_t *)p);
printf ("**note: the will cast result in bytes 4, 3"
" (or (4 << 8 | 3) = 1027)\n\n");
return 0;
}
Output
$ ./bin/cast_array
the uint8_t answer : 3
the uint16_t answer : 1027
**note: the cast will result in bytes 4, 3 (or (4 << 8 | 3) = 1027)
The bytes are stored in memory on my system in little endian
order. So when you cast to uint16_t
it expects to find least significant
, most significant
bytes. Which in the example above with 34
in memory, the cast will interpret the actual order as 43
resulting in a value of 1027
instead of (3 << 8) | 4 = 772
.
As noted, you will be violating rules related to strict aliasing where type pruning by casting to anything other than char
results in undefined behavior. The results of all of these actions are hardware and compiler dependent and should not be used for anything other than a learning exercise.