|
Tous les documents de cette page sont sous licence Creative Commons BY-NC-SA . Merci de la respecter. ©A. Dragut |
This is a little endian machine. ---- same ------ 01110010 Intended number initially nibble-set, in hexa: 72 ---- that is ------ 01110010 Number read back from the nibble, in hexa: 4e ---- which is ------ 01001110et on remarque le fait que l'ordre des bits du dernier message est exactement celui inversé par rapport aux autres énumération de la sortie du programme. (111=7 et 10=2).
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void bits(unsigned char a, const char *m) {
int k;
printf("---- %s ------\n",m);
for(k = 0; k < 8; a <<= 1, k++) {
putchar('0' + ((a&128)>>7)); /* from MSbit to LSbit, for human readability */
}
printf("\n");
}
int main(int argc, char **argv) {
int f = -1;
int k = -1;
const int n = 0x12345678;
const unsigned char b = *(unsigned char *)(&n); /* get the lowest memory address byte */
const unsigned char p = 0x72; /* 0x72 = 01110010 */
const unsigned char q = 0 * 128 + 1*64 + 1*32 + 1*16 + 0*8 + 0*4 + 1*2 + 0*1; /*sum2^n*/
unsigned char r = 0;
struct {
char a:1,b:1,c:1,d:1,e:1,f:1,g:1,h:1;
} t;
if(b == 0x78) {
printf("This is a little endian machine.\n");
}
else {
printf("This is a big endian machine.\n");
}
/* p is 0x72 = 01110010, and '>>' behaves identically regardless of endianness */
bits(p,"same");
/* however, we can show that the bit order is different on Intel than on e.g. SPARC */
/* let us put by hand the bits from 0x72 = 01110010 into 't', nibble by nibble */
t.a = 0; t.b = 1; t.c = 1; t.d = 1; t.e = 0; t.f = 0; t.g = 1; t.h = 0;
/* and "read" it back as a char that "it is" */
r = *(unsigned char *)(&t);
/* and print each of these, as a value and also bit by bit */
printf("Intended number initially nibble-set, in hexa: %x\n",q); /* 0x72 always */
bits(q,"that is");
printf("Number read back from the nibble, in hexa: %x\n",r);
bits(r,"which is"); /* not the same as 'q' on little endian */
return(0);
}