maybe one of you can help me. I don't know what to do anymore. I have the following test code:
#include <stdio.h>
int main() {
unsigned int block = 0;
unsigned int alp = 0;
char *input ="test";
unsigned int *pt = NULL;
pt = (unsigned int*)input;
alp |= ((*pt) >> 8);
printf("pointer value:\t %d \n", alp);
for(int a = 0; a < 3; a ) {
block |= (unsigned char)input[a];
if(a != 2) {
block <<= 8;
}
}
printf("block value:\t %d \n", block);
return 0;
}
I would expect both values to be exactly the same, since they look at exactly 3 bytes. Only the values have a difference. Does anyone have an idea why this is the case or can explain me why?
pointer value: 7631717 block value: 7628147
Compiled with "gcc test.c -Wall -o test" (gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0)
Many thanks
CodePudding user response:
The value of block is
(input[0] << 16) | (input[1] << 8) | (input[2]);
If you're on a little-endian system(which most people are), then the value of alp is
(input[3] << 16) | (input[2] << 8) | (input[1]);
There's nothing fishy going on. the different results are expected on a little-endian system. Your CPU reads the first byte as the least significant one and the last byte as the most significant one, but your for loop reads the first byte as the most significant one and the last byte as the least significant one.