1 8 9 package com.sleepycat.util; 10 11 32 public class PackedInteger { 33 34 39 public static final int MAX_LENGTH = 5; 40 41 50 public static int readInt(byte[] buf, int off) { 51 52 boolean negative; 53 int byteLen; 54 55 int b1 = buf[off++]; 56 if (b1 < -119) { 57 negative = true; 58 byteLen = -b1 - 119; 59 } else if (b1 > 119) { 60 negative = false; 61 byteLen = b1 - 119; 62 } else { 63 return b1; 64 } 65 66 int value = buf[off++] & 0xFF; 67 if (byteLen > 1) { 68 value |= (buf[off++] & 0xFF) << 8; 69 if (byteLen > 2) { 70 value |= (buf[off++] & 0xFF) << 16; 71 if (byteLen > 3) { 72 value |= (buf[off++] & 0xFF) << 24; 73 } 74 } 75 } 76 77 return negative ? (-value - 119) : (value + 119); 78 } 79 80 89 public static int getReadIntLength(byte[] buf, int off) { 90 91 int b1 = buf[off]; 92 if (b1 < -119) { 93 return -b1 - 119 + 1; 94 } else if (b1 > 119) { 95 return b1 - 119 + 1; 96 } else { 97 return 1; 98 } 99 } 100 101 113 public static int writeInt(byte[] buf, int offset, int value) { 114 115 int byte1Off = offset; 116 boolean negative; 117 118 if (value < -119) { 119 negative = true; 120 value = -value - 119; 121 } else if (value > 119) { 122 negative = false; 123 value = value - 119; 124 } else { 125 buf[offset++] = (byte) value; 126 return offset; 127 } 128 offset++; 129 130 buf[offset++] = (byte) value; 131 if ((value & 0xFFFFFF00) == 0) { 132 buf[byte1Off] = negative ? (byte) -120 : (byte) 120; 133 return offset; 134 } 135 136 buf[offset++] = (byte) (value >>> 8); 137 if ((value & 0xFFFF0000) == 0) { 138 buf[byte1Off] = negative ? (byte) -121 : (byte) 121; 139 return offset; 140 } 141 142 buf[offset++] = (byte) (value >>> 16); 143 if ((value & 0xFF000000) == 0) { 144 buf[byte1Off] = negative ? (byte) -122 : (byte) 122; 145 return offset; 146 } 147 148 buf[offset++] = (byte) (value >>> 24); 149 buf[byte1Off] = negative ? (byte) -123 : (byte) 123; 150 return offset; 151 } 152 153 161 public static int getWriteIntLength(int value) { 162 163 if (value < -119) { 164 value = -value - 119; 165 } else if (value > 119) { 166 value = value - 119; 167 } else { 168 return 1; 169 } 170 171 if ((value & 0xFFFFFF00) == 0) { 172 return 2; 173 } 174 if ((value & 0xFFFF0000) == 0) { 175 return 3; 176 } 177 if ((value & 0xFF000000) == 0) { 178 return 4; 179 } 180 return 5; 181 } 182 } 183 | Popular Tags |