首页 > 代码库 > 字节顺序

字节顺序


#include <stdio.h>

typedef int* int_ptr;
typedef unsigned char* byte_ptr;


void show_bytes( byte_ptr start, int len ){

	int i;

	for( i = 0; i < len; ++i ){
		printf( " %4.2x", start[i] );
	}

	printf( "\n" );

}


void show_int( int x ){
	show_bytes( ( byte_ptr ) &x, sizeof( int ) );
}


void show_float( float x ){
	show_bytes( ( byte_ptr ) &x, sizeof( float ) );
}


void show_ptr( void* x ){
	show_bytes( ( byte_ptr ) &x, sizeof( void* ) );
}


void test_show_bytes( int val ){

	int ival   = val;
	float fval = ( float ) ival;
	int* pval  = &ival;

	show_int( ival );
	show_float( fval );
	show_ptr( pval );

}


int main(){

	/*
		Machine | value   | type  | byte( hexadecimal ) |
		-------------------------------------
		Linux   | 12345   | int   | 39 30 00 00
		NT      | 12345   | int   | 39 30 00 00
		Sun     | 12345   | int   | 00 00 30 39 ( big endian )
		Alpha   | 12345   | int   | 39 30 00 00
		--------------------------------------
		Linux   | 12345.0 | float | 00 e4 40 46
		NT      | 12345.0 | float | 00 e4 40 46
		Sun     | 12345.0 | float | 46 40 e4 00
		Alpha   | 12345.0 | float | 00 e4 40 46
		--------------------------------------
		Linux   | &ival   | int*  | 3e fa ff bf
		NT      | &ival   | int*  | 1c ff 44 02
		Sun     | &ival   | int*  | ef ff fc e4
		Alpha   | &ival   | int*  | 80 fc ff 1f 01 00 00 00
	*/

	test_show_bytes( 12345 );

	return 0;

}


字节顺序