HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Find byte[] in byte[] with Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withbytejavafind

Problem

I made a search method because I want to use binary data like PNG files. The point of this is to be able to find strings like IEND in a PNG file. I think it works properly. Any improvements/fixes would be appreciated.

public static int findString(byte[] in, byte[] find) {
        boolean done = false;
        for(int i = 0; i < in.length; i++) {
            if(in[i] == find[0]) {
                for(int ii = 1; ii < find.length; i++) {
                    if(in[i+ii] != find[ii]) break;
                    else if(ii==find.length-1) done = true;
                }
                if(done) return i-1;
            }
        }
        return -1;
    }

Solution

If you want to look for a particular chunk of bytes in a PNG file, don't scan it naïvely byte by byte. Not only would it be slow, you could also accidentally match some data that happens to look like a marker.

Instead, you should take advantage of the chunk layout described in the PNG specification. Each chunk is tagged with a type and a length. If the tag is of a type that you are not interested in, seek ahead to the next chunk — the length field will tell you how many bytes to skip.

Context

StackExchange Code Review Q#46220, answer score: 12

Revisions (0)

No revisions yet.