Search code examples
kotlinbyteprimitivereinterpret-cast

Kotlin Primitives: How to reinterpret ByteArrays as the bits of primitives in Common Multiplatform code?


TL;DR is there an equivalent of C++'s reinterpret_cast<[primitive]>(bytes) for Kotlin Multiplatform?

Basically, what I am looking for is the following functionality:

You have a ByteArray with length, let's say, 4 bytes. The contents are

00 00 00 2A

Then there should be some function or operator to reinterpret these 4 bytes as an Int:

asInt(byteArrayOf(0x00, 0x00, 0x00, 0x2A))

Ideally, there would also be a way to control the Endian-ness of this operation. And most importantly, I'd want this to work on all available platforms (JVM, JS, Native). The question is: Is there such an operation?

Currently, I am doing the following:

  • For the integral types (Byte, Short, Int, Long), I use SHL / OR to construct the actual primitive. But this is of course not as efficient as just reinterpreting (maybe also copying) the value as the primitive value, since the bits are already in the right configuration
  • For the floating-point values, I'm still struggling: So far, I have not found a platform-independent solution, so I use expect / actual. I've found solutions for JVM and JS already (although not that satisfying), but I still don't know how to do it on Native. If it turns out that there is no common solution to the whole problem, I'd be very thankful if someone could point me towards a solution just for Float / Double converting on Native.

Thank you very much!


Solution

  • Your existing solution for integral types is likely to be ideal for multiplatform. For floating point values, you can convert them to and from int/long with Double/Float.fromBits and Double/Float.toRawBits, and then use your existing solution for integral types.