Reputation: 86
I have to do a small assignment for school. I am writing this in C. The question is:
Given
uint16_t A[] = { 0xabce, 0x43fe, 0xcf54, 0xffff };
uint8_t *p = (uint8_t *)&A[0];
What is the value of p[3]
?
I did some research and found that the numbers will be put back into my computer using little-endian. So
p[] = {171, 67, 207, 255}
However, when I print p[]
I get
p[0] = 206
p[1] = 171
p[2] = 254
p[3] = 67
I am very confused by this, can anyone please tell me why this is happening?
Upvotes: 1
Views: 293
Reputation: 110271
So, jsut to be clear - in a little endian machinne, this declaration:
uint16_t A[] = { 0xabce, 0x43fe, 0xcf54, 0xffff };
Will but these bytes in order, in your memory:
ce | ab | fe | 43 | 54 | cf | ff | ff |
(In decimal):
206|171 |254 | 67 | 84 | 207| 255| 255|
So, when you tell the compiler that starting at the very same position in memory, you can read numbers that are one byte long, what is retrievable in your "p" vector are the 8 numbers above.
uint8_t *p = (uint8_t *)&A[0];
(Which could also be written simply uint8_t *p = (uint8_t *)A;
)
Keep in mind that in C, it is the developer's task to know how long a vector is. In this example, it might be that one would have the convention that the number "0xffff" would end the 16bit sequence, for example. Either way, you have twice that number of elements to read as 8 bit.
Upvotes: 3