]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org/argeo/util/BytesUtils.java
Prepare next development cycle
[lgpl/argeo-commons.git] / org / argeo / util / BytesUtils.java
1 package org.argeo.util;
2
3 /** Utilities around byte arrays and byte buffers. */
4 public class BytesUtils {
5 final private static char[] hexArray = "0123456789abcdef".toCharArray();
6
7 /** Convert two longs to a byte array with length 16. */
8 public static byte[] toBytes(long long1, long long2) {
9 byte[] result = new byte[16];
10 for (int i = 0; i < 8; i++)
11 result[i] = (byte) ((long1 >> ((7 - i) * 8)) & 0xff);
12 for (int i = 8; i < 16; i++)
13 result[i] = (byte) ((long2 >> ((15 - i) * 8)) & 0xff);
14 return result;
15 }
16
17 public static void copyBytes(long long1, long long2, byte[] arr, int offset) {
18 assert arr.length >= 16 + offset;
19 for (int i = offset; i < 8 + offset; i++)
20 arr[i] = (byte) ((long1 >> ((7 - i) * 8)) & 0xff);
21 for (int i = 8 + offset; i < 16 + offset; i++)
22 arr[i] = (byte) ((long2 >> ((15 - i) * 8)) & 0xff);
23 }
24
25 /** Converts a byte array to an hex String. */
26 public static String toHexString(byte[] bytes) {
27 char[] hexChars = new char[bytes.length * 2];
28 for (int j = 0; j < bytes.length; j++) {
29 int v = bytes[j] & 0xFF;
30 hexChars[j * 2] = hexArray[v >>> 4];
31 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
32 }
33 return new String(hexChars);
34 }
35
36 /** singleton */
37 private BytesUtils() {
38
39 }
40
41 }