Skip to content

Instantly share code, notes, and snippets.

@ThomasOwens
Last active December 15, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasOwens/5196161 to your computer and use it in GitHub Desktop.
Save ThomasOwens/5196161 to your computer and use it in GitHub Desktop.
Static conversion methods
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.BitSet;
/**
* Utility methods for working with byte arrays.
*
* @author Thomas Owens
*/
public class ByteUtils {
/**
* Convert the specified short value into a byte array.
*
* @param s
* short value to convert
* @return byte array representing the short value
*/
public static byte[] shortToBytes(short s) {
ByteBuffer buff = ByteBuffer.allocate(2);
buff.order(ByteOrder.BIG_ENDIAN);
buff.putShort(s);
return buff.array();
}
/**
* Convert 2 bytes, starting from the specified location in the array, into
* a Short.
*
* @param bytes
* byte array containing the short value
* @param start
* starting index in the array
* @throws IllegalArgumentException
* insufficient bytes to convert
* @throws ArrayIndexOutOfBoundsException
* start offset is negative
* @throws NullPointerException
* the byte array is null
* @return the value as a Short
*/
public static Short bytesToShort(byte[] bytes, int start) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (start < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (bytes.length < (2 + start)) {
throw new IllegalArgumentException(
"Short conversion requires at least 2 bytes after start.");
}
short retValue = 0;
for (int i = 0; i < 2; i++) {
int shift = (2 - 1 - i) * 8;
retValue += (bytes[(i + start)] & 0x00FF) << shift;
}
return retValue;
}
/**
* Convert 2 bytes into a Short.
*
* @param bytes
* byte array containing the short value
* @throws IllegalArgumentException
* insufficient or too many bytes to convert
* @throws ArrayIndexOutOfBoundsException
* start offset is negative
* @throws NullPointerException
* the byte array is null
* @return the value as a Short
*/
public static Short bytesToShort(byte[] bytes) {
if (bytes.length != 2) {
throw new IllegalArgumentException("Short conversion requires 2 bytes.");
}
return bytesToShort(bytes, 0);
}
/**
* Convert the specified character value into a byte array.
*
* @param c
* character value to convert
* @return byte array representing the character value
*/
public static byte[] charToBytes(char c) {
ByteBuffer buff = ByteBuffer.allocate(2);
buff.order(ByteOrder.BIG_ENDIAN);
buff.putChar(c);
return buff.array();
}
/**
* Convert the specified segment of the byte array into a character array.
*
* @param bytes
* byte array containing the characters
* @param startOffset
* starting location in the byte array
* @param endOffset
* ending location in the byte array
* @throws NullPointerException
* the byte array is null
* @throws IllegalArgumentException
* endOffset is at or before startOffset
* @throws ArrayIndexOutOfBoundsException
* startOffset is negative or endOffset is after the end of the
* byte array
* @return a character array representing the specified bytes
*/
public static char[] bytesToCharArray(byte[] bytes, int startOffset,
int endOffset) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (startOffset > endOffset) {
throw new IllegalArgumentException(
"Starting location must be before ending location.");
} else if (startOffset < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (endOffset > bytes.length) {
throw new ArrayIndexOutOfBoundsException(
"End offset must be at or before the end of the array.");
}
char[] tempArray = new char[(endOffset - startOffset) + 1];
int ti = 0;
for (int i = startOffset; i < endOffset;) {
tempArray[ti] = (char) bytes[i];
ti++;
i++;
}
return tempArray;
}
/**
* Convert the specified segment of the byte array into a character array.
*
* @param bytes
* byte array containing the characters
* @throws NullPointerException
* the byte array is null
* @return a character array representing the specified bytes
*/
public static char[] bytesToCharArray(byte[] bytes) {
return bytesToCharArray(bytes, 0, bytes.length);
}
/**
* Convert the specified integer value into a byte array.
*
* @param i
* integer value to convert
* @return byte array representing the integer value
*/
public static byte[] intToBytes(int i) {
ByteBuffer buff = ByteBuffer.allocate(4);
buff.order(ByteOrder.BIG_ENDIAN);
buff.putInt(i);
return buff.array();
}
/**
* Convert 4 bytes, starting from the specified location in the array, into
* an Integer.
*
* @param bytes
* byte array containing the integer value
* @param start
* starting index in the array
* @throws NullPointerException
* byte array is null
* @throws ArrayIndexOutOfBoundsException
* start location is negative
* @throws IllegalArgumentException
* there are insufficient bytes to convert to an integer
* @return the value as an Integer
*/
public static Integer bytesToInt(byte[] bytes, int start) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (start < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (bytes.length < (4 + start)) {
throw new IllegalArgumentException(
"Integer conversion requires at least 4 bytes after start.");
}
int retValue = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
retValue += (bytes[(i + start)] & 0x000000FF) << shift;
}
return retValue;
}
/**
* Convert 4 bytes into an Integer.
*
* @param bytes
* byte array containing the integer value
* @throws NullPointerException
* byte array is null
* @throws IllegalArgumentException
* there are insufficient or too many bytes to convert to an integer
* @return the value as an Integer
*/
public static Integer bytesToInt(byte[] bytes) {
if (bytes.length != 4) {
throw new IllegalArgumentException("Integer conversion requires 4 bytes.");
}
return bytesToInt(bytes, 0);
}
/**
* Convert the specified float value into a byte array.
*
* @param f
* float value to convert
* @return byte array representing the float value
*/
public static byte[] floatToBytes(float f) {
ByteBuffer buff = ByteBuffer.allocate(4);
buff.order(ByteOrder.BIG_ENDIAN);
buff.putFloat(f);
return buff.array();
}
/**
* Convert 4 bytes, starting from the specified location in the array, into
* a Float.
*
* @param bytes
* byte array containing the float value
* @param start
* starting index in the array
* @throws NullPointerException
* byte array is null
* @throws ArrayIndexOutOfBoundsException
* start location is negative
* @throws IllegalArgumentException
* there are insufficient bytes to convert to a float
* @return the value as a Float
*/
public static Float bytesToFloat(byte[] bytes, int start) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (start < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (bytes.length < (4 + start)) {
throw new IllegalArgumentException(
"Float conversion requires at least 4 bytes after start.");
}
byte[] b = new byte[4];
b[3] = bytes[start + 0];
b[2] = bytes[start + 1];
b[1] = bytes[start + 2];
b[0] = bytes[start + 3];
int accum = 0;
int i = 0;
for (int shiftBy = 0; shiftBy < 32; shiftBy += 8) {
accum |= ((long) (b[i] & 0xff)) << shiftBy;
i++;
}
return Float.intBitsToFloat(accum);
}
/**
* Convert 4 bytes into a Float.
*
* @param bytes
* byte array containing the float value
* @throws NullPointerException
* byte array is null
* @throws IllegalArgumentException
* there are insufficient or too many bytes to convert to a float
* @return the value as a Float
*/
public static Float bytesToFloat(byte[] bytes) {
if (bytes.length != 4) {
throw new IllegalArgumentException("Float conversion requires 4 bytes.");
}
return bytesToFloat(bytes, 0);
}
/**
* Convert the specified long value into a byte array.
*
* @param s
* long value to convert
* @return byte array representing the short value
*/
public static byte[] longToBytes(long l) {
ByteBuffer buff = ByteBuffer.allocate(8);
buff.order(ByteOrder.BIG_ENDIAN);
buff.putLong(l);
return buff.array();
}
/**
* Convert 8 bytes, starting from the specified location in the array, into
* a Long.
*
* @param bytes
* byte array containing the long value
* @param start
* starting index in the array
* @throws NullPointerException
* byte array is null
* @throws ArrayIndexOutOfBoundsException
* start location is negative
* @throws IllegalArgumentException
* there are insufficient bytes to convert to a long
* @return the value as a Long
*/
public static Long bytesToLong(byte[] bytes, int start) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (start < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (bytes.length < (8 + start)) {
throw new IllegalArgumentException(
"Long conversion requires at least 8 bytes after start.");
}
byte[] b = new byte[8];
b[0] = bytes[start + 0];
b[1] = bytes[start + 1];
b[2] = bytes[start + 2];
b[3] = bytes[start + 3];
b[4] = bytes[start + 4];
b[5] = bytes[start + 5];
b[6] = bytes[start + 6];
b[7] = bytes[start + 7];
ByteBuffer buf = ByteBuffer.wrap(b);
buf.order(ByteOrder.BIG_ENDIAN);
return buf.getLong();
}
/**
* Convert 8 bytes into a Long.
*
* @param bytes
* byte array containing the long value
* @throws NullPointerException
* byte array is null
* @throws IllegalArgumentException
* there are insufficient bytes to convert to a long
* @return the value as a Long
*/
public static Long bytesToLong(byte[] bytes) {
if (bytes.length != 8) {
throw new IllegalArgumentException("Long conversion requires 8 bytes.");
}
return bytesToLong(bytes, 0);
}
/**
* Convert a double value into a byte array.
*
* @param d
* double value to convert
* @return array representing the specified double value
*/
public static byte[] doubleToBytes(double d) {
ByteBuffer buff = ByteBuffer.allocate(8);
buff.order(ByteOrder.BIG_ENDIAN);
buff.putDouble(d);
return buff.array();
}
/**
* Convert 8 bytes, starting from the specified location in the byte array,
* into a Double.
*
* @param bytes
* byte array containing the double value
* @param start
* starting index in the array
* @throws NullPointerException
* byte array is null
* @throws ArrayIndexOutOfBoundsException
* start location is negative
* @throws IllegalArgumentException
* there are insufficient bytes to convert to a double
* @return the value as a Long
*/
public static Double bytesToDouble(byte[] bytes, int start) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (start < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (bytes.length < (8 + start)) {
throw new IllegalArgumentException(
"Double conversion requires at least 8 bytes after start.");
}
byte[] b = new byte[8];
b[0] = bytes[start + 0];
b[1] = bytes[start + 1];
b[2] = bytes[start + 2];
b[3] = bytes[start + 3];
b[4] = bytes[start + 4];
b[5] = bytes[start + 5];
b[6] = bytes[start + 6];
b[7] = bytes[start + 7];
ByteBuffer buf = ByteBuffer.wrap(b);
buf.order(ByteOrder.BIG_ENDIAN);
return buf.getDouble();
}
/**
* Convert 8 bytes into a Double.
*
* @param bytes
* byte array containing the double value
* @throws NullPointerException
* byte array is null
* @throws IllegalArgumentException
* there are insufficient bytes to convert to a double
* @return the value as a Long
*/
public static Double bytesToDouble(byte[] bytes) {
if (bytes.length != 8) {
throw new IllegalArgumentException("Double conversion requires 8 bytes.");
}
return bytesToDouble(bytes, 0);
}
/**
* Convert a segment of a byte array into a String.
* @param bytes
the byte array containing the String
* @param startOffset
the start location of the String
* @param endOffset
the end location of the String
* @throws NullPointerException
the byte array is null
* @throws IllegalArgumentException
the ending location is before the starting location
* @throws ArrayIndexOutOfBoundsException
the start or end offset is outside of the array
* @return the value as a String
*/
public static String bytesToString(byte[] bytes, int startOffset,
int endOffset) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (startOffset > endOffset) {
throw new IllegalArgumentException(
"Starting location must be before ending location.");
} else if (startOffset < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (endOffset > bytes.length) {
throw new ArrayIndexOutOfBoundsException(
"End offset must be at or before the end of the array.");
}
String retStr;
char[] tempArray = new char[(endOffset - startOffset) + 1];
int ti = 0;
for (int i = startOffset; i < endOffset;) {
tempArray[ti] = (char) bytes[i];
ti++;
i++;
}
retStr = new String(tempArray);
return retStr;
}
/**
* Convert a byte array into a String.
* @param bytes
the byte array containing the String
* @throws NullPointerException
the byte array is null
* @return the value as a String
*/
public static String bytesToString(byte[] bytes) {
return bytesToString(bytes, 0, bytes.length);
}
/**
* Convert a byte array into a hexadecimal String.
*
* @param b
* byte array
* @throws NullPointerException
* byte array is null
* @return hexadecimal representation of the byte array
*/
public static String bytesToHexString(byte[] b) {
if (b == null) {
throw new NullPointerException("Byte array can not be null.");
}
String retVal = "0x";
StringBuffer md = new StringBuffer(32);
for (int i = 0; i < b.length; i++) {
int j = b[i];
if (j < 0) {
j += 256;
}
md.append(hex(j / 16));
md.append(hex(j % 16));
}
retVal = new String("0x" + md.toString());
return retVal;
}
/**
* Convert a series of bytes into a hexadecimal String representation.
*
* @param bytes
* byte array containing the bytes to convert
* @param startOffset
* the starting index of the bytes to convert
* @param endOffset
* the ending index of the bytes to convert
* @throws NullPointerException
* if the byte array is null
* @throws IllegalArgumentException
* if startOffset is greater than endOffset
* @throws ArrayIndexOutOfBoundsException
* if startOffset is before the start of the byte array or
* endOffset is after the end of the byte array
* @return hexadecimal representation of the bytes
*/
public static String bytesToHexStr(byte[] bytes, int startOffset,
int endOffset) {
if (bytes == null) {
throw new NullPointerException("Byte array can not be null.");
} else if (startOffset > endOffset) {
throw new IllegalArgumentException(
"Starting location must be before ending location.");
} else if (startOffset < 0) {
throw new ArrayIndexOutOfBoundsException(
"Start offset must be at least 0.");
} else if (endOffset > bytes.length) {
throw new ArrayIndexOutOfBoundsException(
"End offset must be at or before the end of the array.");
}
int bsize = (endOffset + 1) - startOffset;
byte[] barray = new byte[bsize];
int j = 0;
for (int i = startOffset; i < endOffset + 1;) {
barray[j] = bytes[i];
j++;
i++;
}
return (bytesToHexString(barray));
}
/**
* Convert bytes into a hexadecimal String representation.
*
* @param bytes
* byte array to convert
* @throws NullPointerException
* if the byte array is null
* @return hexadecimal String representation of the bytes
*/
public static String bytesToHexStr(byte[] bytes) {
return bytesToHexStr(bytes, 0, bytes.length);
}
/**
* Convert a single byte into a hexadecimal String.
*
* @param b
* byte to convert
* @throws NullPointerException
* if the byte array is null
* @throws IllegalArgumentException
* if startOffset is greater than endOffset
* @throws ArrayIndexOutOfBoundsException
* if startOffset is before the start of the byte array or
* endOffset is after the end of the byte array
* @return String representation of the byte
*/
public static String aByteToHexStr(byte b) {
byte[] array = new byte[1];
array[0] = b;
return bytesToHexStr(array, 0, 0);
}
/**
* Convert a byte array into a BitSet.
*
* @param bytes
* the byte array to convert into the bit set.
* @return a BitSet representation of the byte array
*/
public static BitSet byteArrayToBitSet(byte[] bytes) {
//TODO Add a byteArrayToBitSet(byte[], int, int) method. Call that
//method here.
if (bytes == null) {
throw new IllegalArgumentException("Byte array can not be null.");
}
BitSet bits = new BitSet();
for (int i = 0; i < bytes.length * 8; i++) {
if ((bytes[bytes.length - i / 8 - 1] & (1 << (i % 8))) > 0) {
bits.set(i);
}
}
return bits;
}
/**
* Convert the specified integer into its corresponding hexadecimal
* character.
*
* @param i
* the integer to convert
* @throws IllegalArgumentException
* if the integer is greater than 15 or less than 0
* @return hex character representation of the integer
*/
private static char hex(int i) {
if (i > 15 || i < 0) {
throw new IllegalArgumentException(
"Can not convert integers larger than 15 to a hex character.");
}
switch (i) {
case 10:
return 'A';
case 11:
return 'B';
case 12:
return 'C';
case 13:
return 'D';
case 14:
return 'E';
case 15:
return 'F';
default:
return (char) (i + 48);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment