setos

拙OS
Log | Files | Refs | LICENSE

endian.c (1394B)


      1 #include <libc.h>
      2 
      3 uint16
      4 endian_little_to_native16(uint16 n)
      5 {
      6 	uint8 *m = (uint8 *) &n;
      7 	return (uint16) m[0] | (uint16) m[1] << 8;
      8 }
      9 
     10 uint16
     11 endian_native_to_little16(uint16 n)
     12 {
     13 	uint8 m[4];
     14 	m[0] = (uint8) n&0x000000ff;
     15 	m[1] = (uint8) ((n&0x0000ff00) >> 8);
     16 	return *(uint16 *)m;
     17 }
     18 
     19 uint32
     20 endian_little_to_native32(uint32 n)
     21 {
     22 	uint8 *m = (uint8 *) &n;
     23 	return (uint32) m[0] | (uint32) m[1] << 8 | (uint32) m[2] << 16 | (uint32) m[3] << 24;
     24 }
     25 
     26 uint32
     27 endian_native_to_little32(uint32 n)
     28 {
     29 	uint8 m[4];
     30 	m[0] = (uint8) n&0x000000ff;
     31 	m[1] = (uint8) ((n&0x0000ff00) >> 8);
     32 	m[2] = (uint8) ((n&0x00ff0000) >> 16);
     33 	m[3] = (uint8) ((n&0xff000000) >> 24);
     34 	return *(uint32 *)m;
     35 }
     36 
     37 uint64
     38 endian_little_to_native64(uint64 n)
     39 {
     40 	uint8 *m = (uint8 *) &n;
     41 	return (uint64) m[0] | (uint64) m[1] << 8 | (uint64) m[2] << 16 |
     42 		(uint64) m[3] << 24 | (uint64) m[4] << 32 | (uint64) m[5] << 40 |
     43 		(uint64) m[6] << 48 | (uint64) m[7] << 56;
     44 }
     45 
     46 uint64
     47 endian_native_to_little64(uint64 n)
     48 {
     49 	uint8 m[4];
     50 	m[0] = (uint8)   n&0x00000000000000ff;
     51 	m[1] = (uint8) ((n&0x000000000000ff00) >> 8);
     52 	m[2] = (uint8) ((n&0x0000000000ff0000) >> 16);
     53 	m[3] = (uint8) ((n&0x00000000ff000000) >> 24);
     54 	m[4] = (uint8) ((n&0x000000ff00000000) >> 32);
     55 	m[5] = (uint8) ((n&0x0000ff0000000000) >> 40);
     56 	m[6] = (uint8) ((n&0x00ff000000000000) >> 48);
     57 	m[7] = (uint8) ((n&0xff00000000000000) >> 56);
     58 	return *(uint64 *)m;
     59 }