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: , , , ,

Oct 02

The Knuth-Morris-Pratt Pattern Matching Algorithm can be used to search a byte array.


public class KPM {
    /**
     * Search the data byte array for the first occurrence 
     * of the byte array pattern.
     */
    public static int indexOf(byte[] data, byte[] pattern) {
        int[] failure = computeFailure(pattern);

        int j = 0;

        for (int i = 0; i < data.length; i++) {
            while (j > 0 && pattern[j] != data[i]) {
                j = failure[j - 1];
            }
            if (pattern[j] == data[i]) { 
                j++; 
            }
            if (j == pattern.length) {
                return i - pattern.length + 1;
            }
        }
        return -1;
    }

    /**
     * Computes the failure function using a boot-strapping process,
     * where the pattern is matched against itself.
     */
    private int[] computeFailure(byte[] pattern) {
        int[] failure = new int[pattern.length];

        int j = 0;
        for (int i = 1; i < pattern.length; i++) {
            while (j>0 && pattern[j] != pattern[i]) {
                j = failure[j - 1];
            }
            if (pattern[j] == pattern[i]) {
                j++;
            }
            failure[i] = j;
        }

        return failure;
    }
}

written by objects \\ tags: , , , ,

May 16

The following code can be used to extract the 8 bytes from a long value and return them as a byte array

public static byte[] longToByteArray(long data) {
    return new byte[] {
        (byte)((data >> 56) & 0xff),
        (byte)((data >> 48) & 0xff),
        (byte)((data >> 40) & 0xff),
        (byte)((data >> 32) & 0xff),
        (byte)((data >> 24) & 0xff),
        (byte)((data >> 16) & 0xff),
        (byte)((data >> 8 ) & 0xff),
        (byte)((data >> 0) & 0xff),
    };
}

written by objects \\ tags: , , , ,