Ok, I feel stupid asking this, but why does the code below output different lines?
To print the first line I take an address to the first byte of an array, interpret it as a pointer to uint16_t, take the value and print it's bits one by one.
For the second line I take a pointer to the first byte, interpret it as a pointer to uint8_t, take the value and print it's bits one by one. Then do the same with the second byte.
As I don't modify memory allocated for an array, only interpret it in different ways, I expect output be the same, but the order of bytes is different.
I probably miss something, but the only guess I have is that indirection operator does something I don't expect.
#include <iostream>
#include <string.h>
int main() {
uint8_t u[2];
u[0] = 170;
u[1] = 85;
for(int i = 15; i >= 0; --i) {
printf( "%u", (((*((uint16_t*)u)) >> i) & 0x0001));
}
printf( "\n");
for(int i = 7; i >= 0; --i) {
printf( "%u", (((*((uint8_t*)u)) >> i) & 0x01));
}
for(int i = 7; i >= 0; --i) {
printf( "%u", (((*((uint8_t*)(u + 1))) >> i) & 0x01));
}
}
Outout
0101010110101010
1010101001010101
Update #1: Please ignore the allocation, yes the example code doesn't work on every os, but it is just a simplified example.
Update #2: I knew about the endianness, but what I missed is logical vs physical bit representation. In the example above even though physical representation is unchanged, I print logical representation that is affected by endianness. Big Thanks to @john-kugelman for explaining that.