Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pointer cast issue (C)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Compiled with "gcc test.c -Wall -o test" (gcc (Ubuntu 12.2.0-3ubuntu1) 12.2.0)

Many thanks

>Solution :

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.

More info on endianness

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading