Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin equivalent of Java's String.getBytes()

Tags:

kotlin

In Java, you can convert a string into an array of its constituent bytes by calling myString.getBytes().

What's the equivalent of this in Kotlin?

like image 842
rmtheis Avatar asked Oct 12 '17 04:10

rmtheis


People also ask

How do you get bytes from String in Kotlin?

To convert a string to byte array in Kotlin, use String. toByteArray() method. String. toByteArray() method returns a Byte Array created using the characters of the calling string.

What is getBytes ()?

The method getBytes() encodes a String into a byte array using the platform's default charset if no argument is passed. We can pass a specific Charset to be used in the encoding process, either as a String object or a String object.

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.


2 Answers

Use the extension String.toByteArray() - which means you will write myString.toByteArray(). Note it defaults to UTF-8 encoding, but you can override this by providing an additional argument.

like image 95
vishal jangid Avatar answered Sep 25 '22 09:09

vishal jangid


For Kotlin use String.toBytesArray(), it will be same as String.getBytes() in Java.

like image 44
fahad.t Avatar answered Sep 26 '22 09:09

fahad.t