Jun 02

## Converting large byte array to binary string

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

Oct 02

## Search a byte array for a byte sequence

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

Oct 01

## How do I convert a JDBC Blob to a byte array?

Read the bytes from the Blob into a ByteArrayOutputStream.

```
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte;

InputStream in = blob.getBinaryStream();

int n = 0;