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. :)
To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.
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.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With