Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Kotlin ByteArray to NsData and viceversa

Fighting with a Kotlin Multiplatform project I have ended with the problem of needing to work with NsData on my iOS platform from the sharedModule working with Kotlin Native.

Because of this, I need to transform objectiveC NsData to Kotlin ByteArray and way back. How can I do this?

like image 865
Francisco Durdin Garcia Avatar asked Oct 23 '19 10:10

Francisco Durdin Garcia


People also ask

How do you convert Bytearray to string in Kotlin?

To convert a byte array to string in Kotlin, use String() constructor. String() constructor can take a Byte Array as argument and return a new string formed with the bytes in the given array.

What is Bytearray in Kotlin?

Creates a new array of the specified size, where each element is calculated by calling the specified init function. Creates a new array of the specified size, with all elements initialized to zero.

How do I declare byte array in Kotlin?

To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.


1 Answers

NsData to ByteArray

actual typealias ImageBytes = NSData
actual fun ImageBytes.toByteArray(): ByteArray = ByteArray([email protected]()).apply {
    usePinned {
        memcpy(it.addressOf(0), [email protected], [email protected])
    }
}

ByteArray to NsData

actual fun ByteArray.toImageBytes(): ImageBytes? = memScoped {
    val string = NSString.create(string = [email protected]())
    return string.dataUsingEncoding(NSUTF8StringEncoding)
}

ByteArray to NsData different way

actual fun ByteArray.toImageBytes() : ImageBytes = memScoped { 
    NSData.create(bytes = allocArrayOf(this@toImageBytes), 
        length = [email protected]()) 
}
like image 121
Francisco Durdin Garcia Avatar answered Sep 17 '22 08:09

Francisco Durdin Garcia