DataConverterLE.java
01 /**
02 * 数据格式转换( byte => short int long float double )
03 * Little Endian 存储方式
04 * PACKAGE : cma.common.dataio
05 * DESCRIPTION : Little Endian 数据格式转换
06 * MODIFIER : 刘泽军
07 * EMAIL : BJ0773@gmail.com
08 * Date : 2007-05-04 00:55:43
09 * Update :
10 * Reference : jxutil.sourceforge.net
11 */
12
13 package cma.common.dataio;
14
15 import java.math.BigInteger;
16
17 public class DataConverterLE {
18 DataConverterLE () {
19 }
20
21 public static String getHex ( byte [] buf ) {
22 return getHex ( buf, 0 , 2 ) ;
23 }
24 public static String getHex ( byte [] buf, int index ) {
25 return getHex ( buf, index, 2 ) ;
26 }
27 public static short getShort ( byte [] buf ) { //2 bytes
28 return getShort ( buf, 0 ) ;
29 }
30 public static int getInt ( byte [] buf ) { //4 bytes
31 return getInt ( buf, 0 ) ;
32 }
33 public static long getLong ( byte [] buf ) { //8 bytes
34 return getLong ( buf, 0 ) ;
35 }
36 public static float getFloat ( byte [] buf ) { //4 bytes
37 return getFloat ( buf, 0 ) ;
38 }
39 public static double getDouble ( byte [] buf ) { //8 bytes
40 return getDouble ( buf, 0 ) ;
41 }
42
43 public static String getHex ( byte [] buf, int ofs, int len ) {
44 String hexStr = "0123456789ABCDEF" ;
45 StringBuffer bufStr = new StringBuffer () ;
46 for ( int i= 0 ;i<len;i++ ) {
47 bufStr.append ( hexStr.charAt (( buf [ ofs + i ] >> 4 ) & 0xf )) ;
48 bufStr.append ( hexStr.charAt ( buf [ ofs + i ] & 0xf )) ;
49 }
50 return ( bufStr.toString ()) ;
51 }
52 public static short getShort ( byte [] buf, int ofs ) {
53 return ( short ) (
54 ( buf [ ofs ] & 0xFF )
55 + (( buf [ ofs+ 1 ] & 0xFF ) << 8 )
56 ) ;
57 }
58 public static int getInt ( byte [] buf, int ofs ) {
59 return (
60 ( buf [ ofs ] & 0xFF )
61 + (( buf [ ofs + 1 ] & 0xFF ) << 8 )
62 + (( buf [ ofs + 2 ] & 0xFF ) << 16 )
63 + (( buf [ ofs + 3 ] & 0xFF ) << 24 )
64 ) ;
65 }
66 public static long getLong ( byte [] buf, int ofs ) {
67 return (
68 (( long ) buf [ ofs ] & 0xFF )
69 + ((( long ) buf [ ofs + 1 ] & 0xFF ) << 8 )
70 + ((( long ) buf [ ofs + 2 ] & 0xFF ) << 16 )
71 + ((( long ) buf [ ofs + 3 ] & 0xFF ) << 24 )
72 + ((( long ) buf [ ofs + 4 ] & 0xFF ) << 32 )
73 + ((( long ) buf [ ofs + 5 ] & 0xFF ) << 40 )
74 + ((( long ) buf [ ofs + 6 ] & 0xFF ) << 48 )
75 + ((( long ) buf [ ofs + 7 ] & 0xFF ) << 56 )
76 ) ;
77 }
78 public static float getFloat ( byte [] buf, int ofs ) {
79 return Float.intBitsToFloat ( getInt ( buf, ofs )) ;
80 }
81 public static double getDouble ( byte [] buf, int ofs ) {
82 return Double.longBitsToDouble ( getLong ( buf, ofs )) ;
83 }
84
85 }