1 package de.dhbwloe.campusapp.nfcreader;
4 * Created by stefan on 20.01.16.
8 * Converts a hex string (Format: "XX XX XX ..") into a Byte array
12 public static Byte[] stringToHex(String hexString) {
13 if (hexString == null)
15 hexString = hexString.replace(" ", "");
16 final int bytesCount = hexString.length() / 2;
17 if (2 * bytesCount != hexString.length()) {
18 throw new IllegalArgumentException(
19 "Hex string must have an even number of digits");
22 Byte[] result = new Byte[bytesCount];
23 for (int i = 0; i < hexString.length(); i += 2) {
24 result[i / 2] = (byte) Integer.parseInt(hexString.substring(i, i + 2), 16);
30 * Converts a Byte array into a hex string (Format "xx xx xx ..")
34 public static String hexToString(Byte[] bytes) {
35 StringBuffer buff = new StringBuffer();
36 for (byte b : bytes) {
37 buff.append(String.format("%02X", b));
39 return buff.toString();
43 * Extracts parts of the Byte array into a seperate array
44 * @param start Start position of sub array
45 * @param stop Stop position of sub array
46 * @param array Array to extract from
49 public static Byte[] subByteArray(int start, int stop, Byte[] array) {
50 Byte[] returnArray = new Byte[stop-start];
52 for (int i = start; i<stop; i++) {
53 returnArray[position] = array[i];
61 * Reverses byte order in byte array (to convert from LSB and MSB and backwards)
62 * @param bytes byte array
63 * @return reversed byte array
65 public static Byte[] reverseByteOrder(Byte[] bytes) {
66 Byte[] returnBytes = new Byte[bytes.length];
67 for (int i=0; i<bytes.length; i++) {
68 returnBytes[bytes.length - 1 - i] = bytes[i];
74 * Converts byte array to integer
78 public static int hexToInteger(Byte[] bytes) {
79 String hexString = hexToString(bytes);
80 return Integer.parseInt(hexString, 16);
84 * Converts a Byte[] array to byte[] array (Object to primitive)
88 public static byte[] bytesToPrimitives(Byte[] oBytes)
90 byte[] bytes = new byte[oBytes.length];
92 for(int i = 0; i < oBytes.length; i++) {
100 * Converts a byte[] array to Byte[] array (Primitive to object)
104 public static Byte[] bytesToObjects(byte[] bytesPrim) {
105 Byte[] bytes = new Byte[bytesPrim.length];
108 for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing
113 public static int byteArrayToInt(byte[] b) {
114 return byteArrayToInt(b, 0);
117 public static int byteArrayToInt(byte[] b, int offset) {
118 return byteArrayToInt(b, offset, b.length);
121 public static int byteArrayToInt(byte[] b, int offset, int length) {
122 return (int) byteArrayToLong(b, offset, length);
125 public static long byteArrayToLong(byte[] b, int offset, int length) {
126 if (b.length < length)
127 throw new IllegalArgumentException("length must be less than or equal to b.length");
130 for (int i = 0; i < length; i++) {
131 int shift = (length - 1 - i) * 8;
132 value += (b[i + offset] & 0x000000FF) << shift;