1 19 package gcc.util; 20 21 public abstract class LittleEndian 22 { 23 public static byte[] getShortBytes(short value) 24 { 25 byte[] bytes = new byte[2]; 26 setShort(bytes, value); 27 return bytes; 28 } 29 30 public static byte[] getIntBytes(int value) 31 { 32 byte[] bytes = new byte[4]; 33 setInt(bytes, value); 34 return bytes; 35 } 36 37 public static byte[] getLongBytes(long value) 38 { 39 byte[] bytes = new byte[8]; 40 setLong(bytes, value); 41 return bytes; 42 } 43 44 public static short getShort(byte[] bytes) 45 { 46 return getShort(bytes, 0); 47 } 48 49 public static short getShort(byte[] bytes, int offset) 50 { 51 int b1 = (bytes[offset + 1] << 8) & 0x0000ff00; 52 int b0 = bytes[offset] & 0x000000ff; 53 return (short)(b1 | b0); 54 } 55 56 public static int getInt(byte[] bytes) 57 { 58 return getInt(bytes, 0); 59 } 60 61 public static int getInt(byte[] bytes, int offset) 62 { 63 int b3 = (bytes[offset + 3] << 24) & 0xff000000; 64 int b2 = (bytes[offset + 2] << 16) & 0x00ff0000; 65 int b1 = (bytes[offset + 1] << 8) & 0x0000ff00; 66 int b0 = bytes[offset] & 0x000000ff; 67 return b3 | b2 | b1 | b0; 68 } 69 70 public static long getLong(byte[] bytes) 71 { 72 return getLong(bytes, 0); 73 } 74 75 public static long getLong(byte[] bytes, int offset) 76 { 77 long hi = getInt(bytes, offset + 4) & 0xffffffffL; 78 long lo = getInt(bytes, offset) & 0xffffffffL; 79 return (lo << 32) | hi; 80 } 81 82 public static void setShort(byte[] bytes, short value) 83 { 84 setShort(bytes, 0, value); 85 } 86 87 public static void setShort(byte[] bytes, int offset, short value) 88 { 89 bytes[offset] = (byte)(value & 0xff); 90 bytes[offset + 1] = (byte)((value >>> 8) & 0xff); 91 } 92 93 public static void setInt(byte[] bytes, int value) 94 { 95 setInt(bytes, 0, value); 96 } 97 98 public static void setInt(byte[] bytes, int offset, int value) 99 { 100 bytes[offset] = (byte)(value & 0xff); 101 bytes[offset + 1] = (byte)((value >>> 8) & 0xff); 102 bytes[offset + 2] = (byte)((value >>> 16) & 0xff); 103 bytes[offset + 3] = (byte)((value >>> 24) & 0xff); 104 } 105 106 public static void setLong(byte[] bytes, long value) 107 { 108 setLong(bytes, 0, value); 109 } 110 111 public static void setLong(byte[] bytes, int offset, long value) 112 { 113 int hi = (int)(value >>> 32); 114 int lo = (int)value; 115 setInt(bytes, offset + 4, hi); 116 setInt(bytes, offset, lo); 117 } 118 } 119 | Popular Tags |