blob: 5d9285e60ce9052c78f994d03e754173731c7b16 [file] [log] [blame]
Nils Diewaldf399a672013-11-18 17:55:22 +00001package de.ids_mannheim.korap.util;
2
3import java.util.*;
4
Nils Diewaldf399a672013-11-18 17:55:22 +00005/**
Nils Diewaldfe6a3652015-02-05 20:34:27 +00006 * A collection of byte and byte array related
7 * utility functions.
Nils Diewaldf399a672013-11-18 17:55:22 +00008 *
Nils Diewaldfe6a3652015-02-05 20:34:27 +00009 * @author diewald
Nils Diewaldf399a672013-11-18 17:55:22 +000010 */
11public class KorapByte {
12
13 /**
14 * Convert an integer to a byte array.
15 *
16 * @param number The number to convert.
Nils Diewaldfe6a3652015-02-05 20:34:27 +000017 * @return The translated byte array.
Nils Diewaldf399a672013-11-18 17:55:22 +000018 */
Nils Diewaldfe6a3652015-02-05 20:34:27 +000019 // Based on
20 // http://www.tutorials.de/java/228129-konvertierung-von-integer-byte-array.html
Nils Diewaldf399a672013-11-18 17:55:22 +000021 public static byte[] int2byte (int number) {
Nils Diewaldfe6a3652015-02-05 20:34:27 +000022 byte[] data = new byte[4];
23 for (int i = 0; i < 4; ++i) {
24 int shift = i << 3; // That's identical to i * 8
25 data[3-i] = (byte)((number & (0xff << shift)) >>> shift);
26 };
27 return data;
Nils Diewaldf399a672013-11-18 17:55:22 +000028 };
29
Nils Diewaldfe6a3652015-02-05 20:34:27 +000030
Nils Diewaldf399a672013-11-18 17:55:22 +000031 /**
32 * Convert a byte array to an integer.
33 *
Nils Diewaldfe6a3652015-02-05 20:34:27 +000034 * @param data The byte array to convert.
35 * @return The translated integer.
Nils Diewaldf399a672013-11-18 17:55:22 +000036 */
Nils Diewaldfe6a3652015-02-05 20:34:27 +000037 // Based on
38 // http://www.tutorials.de/java/228129-konvertierung-von-integer-byte-array.html
Nils Diewaldf399a672013-11-18 17:55:22 +000039 public static int byte2int (byte[] data) {
Nils Diewaldfe6a3652015-02-05 20:34:27 +000040 return byte2int(data, 0);
Nils Diewaldf399a672013-11-18 17:55:22 +000041 };
42
Nils Diewaldf399a672013-11-18 17:55:22 +000043
Nils Diewaldfe6a3652015-02-05 20:34:27 +000044 /**
45 * Convert a byte array to an integer.
46 *
47 * @param data The byte array to convert.
48 * @param offset The byte offset.
49 * @return The translated integer.
50 */
51 // Based on
52 // http://www.tutorials.de/java/228129-konvertierung-von-integer-byte-array.html
53 public static int byte2int (byte[] data, int offset) {
54 int number = 0;
55 int i = (offset * 4);
56 for (; i < 4; ++i)
57 number |= (data[3-i] & 0xff) << (i << 3);
58 return number;
Nils Diewaldf399a672013-11-18 17:55:22 +000059 };
Nils Diewaldf399a672013-11-18 17:55:22 +000060};