Jun 11

You can tell the parseInt() method what base number system is used by the String that is being parsed.


String hex = "01001101";
int n = Integer.parseInt(hex, 2);

written by objects \\ tags: , , , , ,

Jun 02

You can use BigInteger class to convert a byte array into its hex (or binary) representation. However for large byte arrays this method is slow.

For large byte arrays and where performance is important you can use the following utility method to convert each byte to its binary representation.

   public static String toBinaryString(byte n) {
        StringBuilder sb = new StringBuilder("00000000");
        for (int bit = 0; bit < 8; bit++) {
            if (((n >> bit) & 1) > 0) {
                sb.setCharAt(7 - bit, '1');
            }
        }
        return sb.toString();
    }

written by objects \\ tags: , , , ,

Nov 18

The following code can be used to convert a byte array (containing the bytes of a long) into a long.

	public static long byteArrayToLong(byte[] bytes) {
		long l = 0;
		for (int i=0; i<8; i++) {
			l <<= 8;
			l ^= (long) bytes[i] & 0xff;
		}
		return l;
	}

This is the reverse of “How to convert a long to a byte array“.

written by objects \\ tags: , , , ,