[Tfug] Byte Order

rfs_lists at mac.com rfs_lists at mac.com
Thu Nov 16 11:58:33 MST 2006


Hi Jim,
For completeness, the sign is always the MSB, not necessarily the  
leftmost bit, and never the MSB of the low byte.

So -32767 is either
  1000000000000001
or
  0000000110000000
and never
  1000000100000000

Here's a hack that took me longer than it should've:

-----endian.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void print_bits(short int n, char bits);
int p2(int p);

int main(int argc, char *argv[]) {
         union {
                 short int shint;
                 unsigned char bytes[2];
         } u_shint;

         /* get arg or pull something from time() */
         if (argc > 1) {
                 u_shint.shint=atoi(argv[1]);
         } else {
                 u_shint.shint=(int)time(NULL);
                 printf("Using %d:\n", u_shint.shint);
         }

         printf("Apparent bit pattern:\n");
         print_bits(u_shint.shint,16);
         printf("Actual bit pattern:\n");
         print_bits((short int)((u_shint.bytes[0]*256)+u_shint.bytes 
[1]),16);

         printf("This is a ");
         if ( (short int)((int)u_shint.bytes[0]+(int)u_shint.bytes[1] 
*256) == u_shint.shint) {
                 printf("x86 or Alpha system\n");
                 printf("hi=%d lo=%d short int=%d\n", (int) 
u_shint.bytes[1], (unsigned char)u_shint.bytes[0], u_shint.shint);
                 printf("hi: "); print_bits((short int)u_shint.bytes 
[1],8);
                 printf("lo: "); print_bits((short int)u_shint.bytes 
[0],8);
                 printf("On SPARC, MIPS or PPC systems, the actual  
bit pattern would be:\n");
         } else {
                 printf("SPARC, MIPS or PPC system\n");
                 printf("hi=%d lo=%d short int=%d\n", (int) 
u_shint.bytes[0], (unsigned char)u_shint.bytes[1], u_shint.shint);
                 printf("hi: "); print_bits((short int)u_shint.bytes 
[0],8);
                 printf("lo: "); print_bits((short int)u_shint.bytes 
[1],8);
                 printf("On x86 or Alpha systems, the actual bit  
pattern would be:\n");
         }
         print_bits((short int)((u_shint.bytes[1]*256)+u_shint.bytes 
[0]),16);
}

void print_bits(short int n, char bits) {
         char bit;
         int column_value;
         for (bit=bits-1,column_value=p2(bits-1); bit>=0; -- 
bit,column_value>>=1) {
                 printf( ((n & column_value) ? "1" : "0") );
         }
         printf("\n");
}

int p2(int p) {
         int i=0,r=1;
         while (i++!=p) r*=2;
         return r;
}
-----
play:
  cc endian.c -o endian
  ./endian -32767
  ./endian 128
  ./endian 256
  ./endian -1
-- 
Richard Smit


-- 
Richard Smit






More information about the tfug mailing list