Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Double to ByteArray or Array<Byte> Kotlin

Tags:

kotlin

Given a Double

val double = 1.2345

How can I convert that to a Kotlin ByteArray, and/or Array<Byte>?

Whose content would look like the following after converting 1.2345

00111111 11110011 11000000 10000011
00010010 01101110 10010111 10001101

In Java, there is a sollution that involves Double.doubleToLongBits()(A static method of java.lang.Double), but in Kotlin, Double refers to Kotlin.Double, which has no such (or any other useful in this situation) method.

I don't mind if a sollution yields Kotlin.Double inaccessible in this file. :)

like image 729
Caelum Avatar asked Feb 14 '16 19:02

Caelum


People also ask

How do I make a 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.

How do I convert an image to a Bytearray?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

How do you convert Bytearrays to strings?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


1 Answers

It looks like some convinient methods were added since your answer and you can achieve the same with

val double = 1.2345
ByteBuffer.allocate(java.lang.Double.BYTES)
     .putDouble(double).array()
like image 60
firen Avatar answered Sep 19 '22 14:09

firen