KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > Conversion


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util;
5
6 import com.tc.bytes.TCByteBuffer;
7 import com.tc.exception.TCRuntimeException;
8
9 import java.io.UnsupportedEncodingException JavaDoc;
10
11 /**
12  * Data conversion algorithms and whatnot can be found in java.io.DataInput and
13  * java.io.DataOutput. Contains methods for converting from one kind of thing to another.
14  *
15  * @author orion
16  */

17 public class Conversion {
18
19   public static final long MIN_UINT = 0;
20   public static final long MAX_UINT = 4294967295L; // 2^32 - 1
21

22   private static int makeInt(byte b3, byte b2, byte b1, byte b0) {
23     return ((((b3 & 0xff) << 24) | ((b2 & 0xff) << 16) | ((b1 & 0xff) << 8) | ((b0 & 0xff) << 0)));
24   }
25
26   public static byte setFlag(byte flags, int offset, boolean value) {
27     if (value) {
28       return (byte) (flags | offset);
29     } else {
30       return (byte) (flags & ~offset);
31     }
32   }
33
34   public static boolean getFlag(byte flags, int offset) {
35     return (flags & offset) == offset;
36   }
37
38   /**
39    * Helper method to convert a byte to an unsigned int. Use me when you want to treat a java byte as unsigned
40    */

41   public static short byte2uint(byte b) {
42     return (short) (b & 0xFF);
43   }
44
45   public static long bytes2uint(byte b[]) {
46     return bytes2uint(b, 0, b.length);
47   }
48
49   public static long bytes2uint(byte b[], int length) {
50     return bytes2uint(b, 0, length);
51   }
52
53   /**
54    * Helper method to convert 1-4 bytes (big-endiand) into an unsigned int (max: 2^32 -1)
55    */

56   public static long bytes2uint(byte b[], int offset, int length) {
57     if ((length < 1) || (length > 4)) { throw new IllegalArgumentException JavaDoc("invalid byte array length: " + length); }
58
59     if ((b.length - offset) < length) { throw new IllegalArgumentException JavaDoc("not enough data available for length "
60                                                                            + length + " starting at offset " + offset
61                                                                            + " in a byte array of length " + b.length); }
62
63     long rv = 0;
64
65     switch (length) {
66       case 1: {
67         return byte2uint(b[offset]);
68       }
69       case 2: {
70         rv += ((long) byte2uint(b[0 + offset])) << 8;
71         rv += byte2uint(b[1 + offset]);
72         return rv;
73       }
74       case 3: {
75         rv += ((long) byte2uint(b[0 + offset])) << 16;
76         rv += ((long) byte2uint(b[1 + offset])) << 8;
77         rv += byte2uint(b[2 + offset]);
78         return rv;
79       }
80       case 4: {
81         rv += ((long) byte2uint(b[0 + offset])) << 24;
82         rv += ((long) byte2uint(b[1 + offset])) << 16;
83         rv += ((long) byte2uint(b[2 + offset])) << 8;
84         rv += byte2uint(b[3 + offset]);
85         return rv;
86       }
87       default: {
88         throw new RuntimeException JavaDoc("internal error");
89       }
90     }
91   }
92
93   /**
94    * Helper method to write a 4 byte unsigned integer value into a given byte array at a given offset
95    *
96    * @param l the unsigned int value to write
97    * @param dest the byte array to write the uint into
98    * @param index starting offset into the destination byte array
99    */

100   public static void writeUint(long l, byte[] dest, int index) {
101     if ((l > MAX_UINT) || (l < 0)) { throw new IllegalArgumentException JavaDoc("unsigned integer value invalid: " + l); }
102
103     int pos = index;
104
105     dest[pos++] = (byte) ((l >>> 24) & 0x000000FF);
106     dest[pos++] = (byte) ((l >>> 16) & 0x000000FF);
107     dest[pos++] = (byte) ((l >>> 8) & 0x000000FF);
108     dest[pos++] = (byte) (l & 0x000000FF);
109
110     return;
111   }
112
113   /**
114    * Helper method to write a 4 byte java (signed) integer value into a given byte array at a given offset
115    *
116    * @param l the signed int value to write
117    * @param dest the byte array to write the uint into
118    * @param index starting offset into the destination byte array
119    */

120   public static void writeInt(int i, byte[] dest, int index) {
121     int pos = index;
122
123     dest[pos++] = (byte) ((i >>> 24) & 0x000000FF);
124     dest[pos++] = (byte) ((i >>> 16) & 0x000000FF);
125     dest[pos++] = (byte) ((i >>> 8) & 0x000000FF);
126     dest[pos++] = (byte) ((i >>> 0) & 0x000000FF);
127
128     return;
129   }
130
131   /**
132    * Helper method to convert an unsigned short to 2 bytes (big-endian)
133    */

134   public static byte[] ushort2bytes(int i) {
135     if ((i > 0xFFFF) || (i < 0)) { throw new IllegalArgumentException JavaDoc("invalid short value: " + i); }
136
137     byte[] rv = new byte[2];
138
139     rv[0] = (byte) ((i >>> 8) & 0x000000FF);
140     rv[1] = (byte) ((i >>> 0) & 0x000000FF);
141
142     return rv;
143   }
144
145   /**
146    * Helper method to convert an unsigned integer to 4 bytes (big-endian)
147    */

148   public static byte[] uint2bytes(long l) {
149     if ((l > MAX_UINT) || (l < 0)) { throw new IllegalArgumentException JavaDoc("unsigned integer value out of range: " + l); }
150
151     byte[] rv = new byte[4];
152
153     rv[0] = (byte) ((l >>> 24) & 0x000000FF);
154     rv[1] = (byte) ((l >>> 16) & 0x000000FF);
155     rv[2] = (byte) ((l >>> 8) & 0x000000FF);
156     rv[3] = (byte) ((l >>> 0) & 0x000000FF);
157
158     return rv;
159   }
160
161   /**
162    * Helper method to convert a string to bytes in a safe way.
163    */

164   public static String JavaDoc bytes2String(byte[] bytes) {
165     try {
166       return new String JavaDoc(bytes, "UTF-8");
167     } catch (UnsupportedEncodingException JavaDoc e) {
168       throw new TCRuntimeException(e);
169     }
170   }
171
172   /**
173    * Helper method to convert a string to bytes in a safe way.
174    */

175   public static byte[] string2Bytes(String JavaDoc string) {
176     try {
177       return (string == null) ? new byte[0] : string.getBytes("UTF-8");
178     } catch (UnsupportedEncodingException JavaDoc e) {
179       throw new TCRuntimeException(e);
180     }
181   }
182
183   public static boolean bytes2Boolean(byte[] bytes) {
184     return (bytes[0] != 0 ? true : false);
185   }
186
187   public static byte[] boolean2Bytes(boolean v) {
188     byte[] rv = new byte[1];
189
190     rv[0] = v ? (byte) 1 : (byte) 0;
191     return rv;
192   }
193
194   public static byte[] byte2Bytes(byte v) {
195     return new byte[] { v };
196   }
197
198   public static char bytes2Char(byte[] bytes) {
199     return (char) ((bytes[0] << 8) | (bytes[1] & 0xff));
200   }
201
202   public static byte[] char2Bytes(char v) {
203     return new byte[] { (byte) (0xff & (v >> 8)), (byte) (0xff & v) };
204   }
205
206   public static double bytes2Double(byte[] bytes) {
207     return Double.longBitsToDouble(Conversion.bytes2Long(bytes));
208   }
209
210   public static byte[] double2Bytes(double l) {
211     return Conversion.long2Bytes(Double.doubleToLongBits(l));
212   }
213
214   public static float bytes2Float(byte[] bytes) {
215     return Float.intBitsToFloat(Conversion.bytes2Int(bytes));
216   }
217
218   public static byte[] float2Bytes(float l) {
219     return Conversion.int2Bytes(Float.floatToIntBits(l));
220   }
221
222   public static int bytes2Int(byte[] bytes, int offset) {
223     return makeInt(bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]);
224   }
225
226   public static int bytes2Int(byte[] bytes) {
227     return makeInt(bytes[0], bytes[1], bytes[2], bytes[3]);
228   }
229
230   public static byte[] int2Bytes(int v) {
231     byte[] rv = new byte[4];
232
233     rv[0] = (byte) ((v >>> 24) & 0xFF);
234     rv[1] = (byte) ((v >>> 16) & 0xFF);
235     rv[2] = (byte) ((v >>> 8) & 0xFF);
236     rv[3] = (byte) ((v >>> 0) & 0xFF);
237
238     return rv;
239   }
240
241   public static long bytes2Long(byte[] bytes) {
242     return (((long) bytes[0] << 56) + ((long) (bytes[1] & 0xFF) << 48) + ((long) (bytes[2] & 0xFF) << 40)
243             + ((long) (bytes[3] & 0xFF) << 32) + ((long) (bytes[4] & 0xFF) << 24) + ((bytes[5] & 0xFF) << 16)
244             + ((bytes[6] & 0xFF) << 8) + ((bytes[7] & 0xFF) << 0));
245   }
246
247   public static byte[] long2Bytes(long l) {
248     byte[] rv = new byte[8];
249
250     rv[0] = (byte) (l >>> 56);
251     rv[1] = (byte) (l >>> 48);
252     rv[2] = (byte) (l >>> 40);
253     rv[3] = (byte) (l >>> 32);
254     rv[4] = (byte) (l >>> 24);
255     rv[5] = (byte) (l >>> 16);
256     rv[6] = (byte) (l >>> 8);
257     rv[7] = (byte) (l >>> 0);
258
259     return rv;
260   }
261
262   public static short bytes2Short(byte[] bytes) {
263     short rv = (short) (((bytes[0] & 0xFF) << 8) + ((bytes[1] & 0xFF) << 0));
264     return rv;
265   }
266
267   public static byte[] short2Bytes(short v) {
268     byte[] rv = new byte[2];
269
270     rv[0] = (byte) ((v >>> 8) & 0xFF);
271     rv[1] = (byte) ((v >>> 0) & 0xFF);
272
273     return rv;
274   }
275
276   public static boolean byte2Boolean(byte b) {
277     return b != 0;
278   }
279
280   /**
281    * @param value
282    */

283   public static byte boolean2Byte(boolean value) {
284     return (value) ? (byte) 1 : (byte) 0;
285   }
286
287   /**
288    * Equivalent to calling <code>bytesToHex(b, 0, b.length)</code>.
289    */

290   public static String JavaDoc bytesToHex(byte[] b) {
291     return bytesToHex(b, 0, b.length);
292   }
293
294   /**
295    * Converts a single byte to a hex string representation, can be decoded with Byte.parseByte().
296    *
297    * @param b the byte to encode
298    * @return a
299    */

300   public static String JavaDoc bytesToHex(byte[] b, int index, int length) {
301     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
302     byte leading, trailing;
303     for (int pos = index; pos >= 0 && pos < index + length && pos < b.length; ++pos) {
304       leading = (byte) ((b[pos] >>> 4) & 0x0f);
305       trailing = (byte) (b[pos] & 0x0f);
306       buf.append((0 <= leading) && (leading <= 9) ? (char) ('0' + leading) : (char) ('A' + (leading - 10)));
307       buf.append((0 <= trailing) && (trailing <= 9) ? (char) ('0' + trailing) : (char) ('A' + (trailing - 10)));
308     }
309     return buf.toString();
310   }
311
312   /**
313    * @param hexString
314    * @return an array of bytes, decoded from the hex-encoded string, if <code>hexString</code> is <code>null</code>
315    * or the length is not a multiple of two then <code>null</code> is returned.
316    */

317   public static byte[] hexToBytes(String JavaDoc hexString) {
318     if (hexString == null || hexString.length() % 2 != 0) { return null; }
319     int length = hexString.length();
320     byte rv[] = new byte[length / 2];
321     int x, y;
322     for (x = 0, y = 0; x < length; x += 2, ++y) {
323       rv[y] = Byte.parseByte(hexString.substring(x, x + 2), 16);
324     }
325     return rv;
326   }
327
328   public static String JavaDoc buffer2String(int length, TCByteBuffer buffer) {
329     byte[] bytes = new byte[length];
330     buffer.get(bytes);
331     return Conversion.bytes2String(bytes);
332   }
333 }
Popular Tags