Skip to content

Instantly share code, notes, and snippets.

@JohnAZoidberg
Last active February 19, 2016 23:05
Show Gist options
  • Save JohnAZoidberg/39e92b14c0d8f80343e0 to your computer and use it in GitHub Desktop.
Save JohnAZoidberg/39e92b14c0d8f80343e0 to your computer and use it in GitHub Desktop.
Some useful methods for handling byte arrays.
package de.struckmeierfliesen.nxt.linefollower;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class ByteUtils {
private ByteUtils() {}
private static final byte MAX_BYTE = (byte) 0xff;
private static final byte NULL = 0x00 & MAX_BYTE;
private static final byte START_OF_HEADER = 0x01 & MAX_BYTE;
private static final byte START_OF_CONTENT = 0x02 & MAX_BYTE;
private static final byte END_OF_MESSAGE = 0x03 & MAX_BYTE;
private static final int SIZEOF_LONG = Long.SIZE / Byte.SIZE;
public static byte[] listToArray(List<Byte> list) {
byte[] bytes = new byte[list.size()];
for (int i = 0; i < list.size(); i++) {
bytes[i] = list.get(i);
}
return bytes;
}
public static String arrayToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}
public static String listToString(List<Byte> list) {
return arrayToString(listToArray(list));
}
public static byte[] packMessage(byte[] header, byte[] content) {
int length = header.length + content.length + 3;
List<Byte> bytes = new ArrayList<>(length);
bytes.add(START_OF_HEADER);
for (byte b : header) bytes.add(b);
bytes.add(START_OF_CONTENT);
for (byte b : content) bytes.add(b);
bytes.add(END_OF_MESSAGE);
return listToArray(bytes);
}
public static byte[][] unpackMessage(byte[] bytes) {
List<Byte> header = new ArrayList<>();
List<Byte> content = new ArrayList<>();
byte lastDescriptor = NULL;
loop: for (byte b : bytes) {
switch (lastDescriptor) {
case NULL:
if (b == START_OF_HEADER) {
lastDescriptor = b;
}
break;
case START_OF_HEADER:
if (b == START_OF_CONTENT) {
lastDescriptor = b;
} else {
header.add(b);
}
break;
case START_OF_CONTENT:
if (b == END_OF_MESSAGE) {
lastDescriptor = b;
}else {
content.add(b);
}
break;
case END_OF_MESSAGE:
break loop;
}
}
return new byte[][] {listToArray(header), listToArray(content)};
}
public static byte[] longToBytes(long val) { // taken from org.apache.hadoop.hbase.util.Bytes
byte [] b = new byte[8];
for (int i = 7; i > 0; i--) {
b[i] = (byte) val;
val >>>= 8;
}
b[0] = (byte) val;
return b;
}
public static long bytesToLong(byte[] bytes) { // taken from org.apache.hadoop.hbase.util.Bytes
long l = 0;
for(int i = 0; i < SIZEOF_LONG; i++) {
l <<= 8;
l ^= bytes[i] & 0xFF;
}
return l;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment