OT: Requesting C advice

Andy Green andy at warmcat.com
Thu May 24 07:10:55 UTC 2007


Michael Hennebry wrote:

>> printf("%d\n",-2);
>>
>> does not result in
>>
>> -2
> 
> It should.
> printf, declared or not, will look for an int and get it.
> 
> printf("%u\n", -2);
> is more interesting.

That will do exactly the same on big and little-endian machines too, if
the int size is the same.

It's only the bytewise layout in memory that is different, and if the
compiler is putting it into registers or memory in one order and reading
it back out in the same order -- for either order -- it's invisible what
the endian-ness is.  You have to violate that in some way like this too
get a problem

{
    int n1 = 1234, n2;
    unsigned char * pc = (unsigned char *)&n1;
    /* assumption about byte ordering that is wrong for big-endian */
    n2 = pc[0] | (pc[1] >> 8) | (pc[2] >> 16) | (pc[3] >> 24);
    printf("n1=0x%X, n2=0x%X\n", n1, n2);
}

-Andy




More information about the fedora-list mailing list