Franch
Franch

Reputation: 651

Hexadecimal values as Strings C

I'm doing an essay for my university and have run into some confusion.

int main(void) {
unsigned int i = 0x00646c72;
printf("H%x Wo%s\n", 57616, (char *) &i);
}

Basically in a little endian arquitecture this prints out: He110 World

I have to tell what would this print if this piece of code was executed by a Big Endian arquitecture.

So far what I know:

'H', space, 'W' and 'o' would remain where they are because of being a string literal in 8-bit representation.

The value 57616 in base 16 is e110. This in my knowledge should be stored in little endian as 10e1, but still it's printed as 'e110', maybe it has to do with how the %x formatter works?

0x00646c72 translates to ASCII as 'dlr' so in little endian it reads 'rld' but in Big Endian it would print 'dlr'. Are this asumptions correct?

Finally in a very related question:

#define VGABUF ((void *) 0xb8000)

void begin(void) {
    int *vga = VGABUF;
    *vga = 0x2f4b2f4f;

    while (1)
        continue;
}

I'm asked to modify this code (which shows an OK sign with green background) to behave exactly the same in a Big Endian arquitecture. I'm thinking I should write vga as a string literal but when I tried it, it did not print anything.

Upvotes: 0

Views: 606

Answers (1)

Tommylee2k
Tommylee2k

Reputation: 2731

The value 57616 in base 16 is e110. This in my knowledge should be stored in little endian as 10e1, but still it's printed as 'e110', maybe it has to do with how the %x formatter works?

correct, how it's printed has nothing to do with endianess, this will not change on a big endian machine.

0x00646c72 translates to ASCII as 'dlr' so in little endian it reads 'rld' but in Big Endian it would print 'dlr'. Are this asumptions correct?

you forgot the 0x00 at the beginning. casted to (char *) this is "rld" + terminating 0. if you have big endian, you will get 0, 0x64, 0x6c, 0x72, the terminating 0 will be the first char, and the string printed will be empty

so the result will be "he110 wo\n"

Upvotes: 1

Related Questions