Kotlin: Convert a string to Byte Array and pad it out with 0's

Viewed 711

I am trying to convert some iOS code to Kotlin. What I believe the iOS code does is takes a string (FrameNumber) converts it to NSData and pads it out with 0's to be 16 bytes long.

//iOS

let frameNumber = "590636"

var frameData = frameNumber.data(using: .utf8)!
let a = Data(repeating: 0, count: 16 - frameData.count)
frameData.append(a)

I cant seem to find a way to do this in Kotlin

var frame = "590636"
        var byteArray = frame.toByteArray()

        // improve
        byteArray.set(7 ,0)
        byteArray.set(8 ,0)
        byteArray.set(9 ,0)
        byteArray.set(10 ,0)
        byteArray.set(11 ,0)
        byteArray.set(12 ,0)
        byteArray.set(13 ,0)
        byteArray.set(14 ,0)
        byteArray.set(15 ,0)
        byteArray.set(156,0)

        Log.i("Code was", "${byteArray.toHexString()}")
1 Answers

You can use copyOf(newSize) with the new size you expect:

val frame = "590636"
val byteArray = frame.toByteArray()
val paddedArray = byteArray.copyOf(newSIze = 16)

If the source array is smaller than 16 bytes, the end of the new array will be padded with 0s.

Related