as an option you can create simple function
fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() }
and use it
val arr = byteArrayOfInts(0xA1, 0x2E, 0x38, 0xD4, 0x89, 0xC3)
Answer from user10053723 on Stack Overflow Top answer 1 of 5
54
as an option you can create simple function
fun byteArrayOfInts(vararg ints: Int) = ByteArray(ints.size) { pos -> ints[pos].toByte() }
and use it
val arr = byteArrayOfInts(0xA1, 0x2E, 0x38, 0xD4, 0x89, 0xC3)
2 of 5
45
If all your bytes were less than or equal to 0x7F, you could put them directly:
byteArrayOf(0x2E, 0x38)
If you need to use bytes greater than 0x7F, you can use unsigned literals to make a UByteArray and then convert it back into a ByteArray:
ubyteArrayOf(0xA1U, 0x2EU, 0x38U, 0xD4U, 0x89U, 0xC3U).toByteArray()
I think it's a lot better than appending .toByte() at every element, and there's no need to define a custom function as well.
However, Kotlin's unsigned types are an experimental feature, so you may have some trouble with warnings.
Baeldung
baeldung.com › home › kotlin › kotlin arrays › creating a byte array in kotlin
Creating a Byte Array in Kotlin | Baeldung on Kotlin
March 19, 2024 - val concatenatedArray = ByteArray(byteArray.size + bytesToAdd.size) byteArray.copyInto(concatenatedArray) bytesToAdd.copyInto(concatenatedArray, destinationOffset = byteArray.size) We must note that we don’t need to specify the destinationOffset argument for the first copy operation, as the default offset is 0. However, we need to explicitly specify the destinationOffset for the subsequent copy operations to ensure we don’t override existing bytes. Since Kotlin is fully interoperable with Java, we can use Java classes and libraries to solve our use case.
What is a byte array in Kotlin?
A byte array in Kotlin is a collection of bytes, where each element represents an 8-bit signed integer. It is used for storing binary data such as files, network streams, or raw byte sequences. Byte arrays are particularly useful for handling data at a low level, allowing precise control over memory and binary data manipulation.
dhiwise.com
dhiwise.com › post › the-basics-of-kotlin-bytearray-easy-steps-to-get-started
Starting with Kotlin ByteArray: A Beginner's Guide
How to create an empty byte array in Kotlin?
You can create an empty byte array in Kotlin using `ByteArray(0)`. This creates a byte array with a length of zero, meaning it contains no elements. It’s useful when you need a placeholder for byte data that will be populated later.
dhiwise.com
dhiwise.com › post › the-basics-of-kotlin-bytearray-easy-steps-to-get-started
Starting with Kotlin ByteArray: A Beginner's Guide
How to write byte array to file in Kotlin?
To write a byte array to a file in Kotlin, use Kotlin’s `writeBytes()` method. This method takes a byte array and writes it directly to a file, making it easy to store binary data such as images or text files in a compact format.
dhiwise.com
dhiwise.com › post › the-basics-of-kotlin-bytearray-easy-steps-to-get-started
Starting with Kotlin ByteArray: A Beginner's Guide
Kotlin Discussions
discuss.kotlinlang.org › t › java-byte-and-kotlin-bytearray-question › 1065
Java byte[] and Kotlin ByteArray question - Kotlin Discussions
October 13, 2012 - I am trying to convert the Java method below into Kotlin one and I have dificulties doing so. Issues are commented at the end of every troubled line. Any hint or idea will do Java code: public static ByteArrayOutputStream convert(InputStream stream) { final ByteArrayOutputStream out = new ByteArrayOutputStream(8192); byte buffer = new byte[8192]; int length; try { while ((length = stream.read(buffer)) > 0) { out.write(buffer, 0, length); } out.flush(); ...
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin › -byte-array
ByteArray
Represents an array (specifically, a Java array when targeting the JVM platform). Array instances can be created using the arrayOf, arrayOfNulls and emptyArray standard library functions. See Kotlin language documentation for more information on arrays.
Baeldung
baeldung.com › home › kotlin › kotlin strings › convert a string to a byte array in kotlin
Convert a String to a Byte Array in Kotlin | Baeldung on Kotlin
March 11, 2024 - The Kotlin language provides a straightforward solution for this case. The String class provides a toByteArray() method. It converts the String object to a byte array object. Moreover, it converts the object using the UTF-8 Charset.
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.collections › to-byte-array.html
toByteArray | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.collections/toByteArray · fun Array<out Byte>.toByteArray(): ByteArray(source) Returns an array of Byte containing all of the elements of this generic array.
Baeldung
baeldung.com › home › kotlin › kotlin io › convert file to byte array in kotlin
Convert File to Byte Array in Kotlin | Baeldung on Kotlin
January 31, 2024 - A quick tutorial on converting a file to a byte array in Kotlin.
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.random › -random › next-bytes.html
nextBytes - Kotlin Programming Language
Try the revamped Kotlin docs design! ... open fun nextBytes( array: ByteArray, fromIndex: Int = 0, toIndex: Int = array.size ): ByteArray (source)
Programiz
programiz.com › kotlin-programming › examples › convert-file-byte-array
Kotlin Program to Convert File to byte array and Vice-Versa
In this program, you'll learn to convert a File object to byte[] and vice-versa in Kotlin.
Android Developers
developer.android.com › api reference › bytearrayoutputstream
ByteArrayOutputStream | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin › byte-array-of.html
byteArrayOf | Core API – Kotlin Programming Language
import kotlin.test.* fun main() ... } actual fun byteArrayOf(vararg elements: Byte): ByteArray(source) Returns an array containing the specified Byte numbers....
DhiWise
dhiwise.com › post › how-to-easily-convert-kotlin-bytearray-to-string
Convert Kotlin ByteArray to String: A Developer Guide
November 11, 2024 - The simplest way to convert a bytearray into a string is by using the default charset. In Kotlin, the ByteArray class provides a toString method, but it’s not suitable for direct conversion because it does not decode bytes into readable characters.
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.collections › to-u-byte-array.html
toUByteArray | Core API – Kotlin Programming Language
kotlin-stdlib/kotlin.collections/toUByteArray · @ExperimentalUnsignedTypesfun Array<out UByte>.toUByteArray(): UByteArray(source) Returns an array of UByte containing all of the elements of this generic array. 1.3 · @ExperimentalUnsignedTypesinline fun ByteArray.toUByteArray(): UByteArray(source) Returns an array of type UByteArray, which is a copy of this array where each element is an unsigned reinterpretation of the corresponding element of this array.
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin › byte-array-of.html
byteArrayOf - Kotlin Programming Language
October 13, 2012 - kotlin-stdlib / kotlin / byteArrayOf · Common · JVM · JS · Native ·
Kotlin
kotlinlang.org › api › kotlinx.serialization › kotlinx-serialization-core › kotlinx.serialization › decode-from-byte-array.html
decodeFromByteArray | kotlinx.serialization – Kotlin Programming Language
kotlinx-serialization-core/kotlinx.serialization/decodeFromByteArray · inline fun <T> BinaryFormat.decodeFromByteArray(bytes: ByteArray): T(source) Decodes and deserializes the given byte array to the value of type T using deserializer retrieved from the reified type parameter.
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.text › encode-to-byte-array.html
encodeToByteArray | Core API – Kotlin Programming Language
expect fun String.encodeToByteArray(startIndex: Int = 0, endIndex: Int = this.length, throwOnInvalidSequence: Boolean = false): ByteArray(source) Encodes this string or its substring to an array of bytes in UTF-8 encoding.
Kotlin
kotlinlang.org › api › latest › jvm › stdlib › kotlin.collections › to-string.html
toString - Kotlin Programming Language
import java.util.Locale import kotlin.test.* fun main(args: Array<String>) { //sampleStart val charset = Charsets.UTF_8 val byteArray = "Hello".toByteArray(charset) println(byteArray.contentToString()) // [72, 101, 108, 108, 111] println(byteArray.toString(charset)) // Hello //sampleEnd }