3

I need to find a sequence of bytes within a ByteArray, but there doesn't seem to be any direct operations to do so. What's the most direct route to determining if a particular sequence of bytes exists within a ByteArray?

For example, I'd like to capture the range of a sequence (or null) with something like this:

val searchArray = arrayOf(0xF1.toByte(), 0xF2.toByte(), 0xF4.toByte(), 0xF8.toByte())
val range = myByteArray.range(of: searchArray)

I'd also be happy with just the starting index, since I always know the size of my search array.

Alec Sanger
  • 4,442
  • 1
  • 33
  • 53
  • 1
    Maybe you can do it by converting your Byte array to String then use the string methods to find the index – vincrichaud Feb 18 '19 at 15:26
  • I'll let this here... http://helpdesk.objects.com.au/java/search-a-byte-array-for-a-byte-sequence – aran Feb 18 '19 at 15:28
  • 1
    https://stackoverflow.com/questions/3940194/find-an-array-inside-another-larger-array – GriffeyDog Feb 18 '19 at 15:31
  • 2
    Thanks @GriffeyDog - your link got me to the solution that worked the best for my situation. Since I'm doing Android dev, I have access to Google Guava, which provides `Bytes.indexOf(ByteArray, ByteArray)`. – Alec Sanger Feb 18 '19 at 15:41
  • 1
    @AlecSanger pls, create an answer for this :) – Willi Mentzel Feb 20 '19 at 18:49

1 Answers1

4

its too simple to add guava just for it:

fun ByteArray.findFirst(sequence: ByteArray,startFrom: Int = 0): Int {
    if(sequence.isEmpty()) throw IllegalArgumentException("non-empty byte sequence is required")
    if(startFrom < 0 ) throw IllegalArgumentException("startFrom must be non-negative")
    var matchOffset = 0
    var start = startFrom
    var offset = startFrom
    while( offset < size ) {
        if( this[offset] == sequence[matchOffset]) {
            if( matchOffset++ == 0 ) start = offset
            if( matchOffset == sequence.size ) return start
        }
        else
            matchOffset = 0
        offset++
    }
    return -1
}
sergeych
  • 791
  • 7
  • 11