rshah
March 4, 2014, 10:08am
1
Hi,
I have this java function
public static int bytesToUnsignedShort(byte byte1, byte byte2, boolean bigEndian) {
if (bigEndian)
return ( ( (byte1 & 0xFF) << 8) | (byte2 & 0xFF) );
return ( ( (byte2 & 0xFF) << 8) | (byte1 & 0xFF) );
}
How to achieve similar result in kotlin way, i mean using native kotlin function instead of porting it like below:
public fun bytesToUnsignedShort(byte1 : Byte, byte2 : Byte, bigEndian : Boolean) : Int {
if (bigEndian)
return (((byte1.toInt() and 255) shl 8) or (byte2.toInt() and 255))
return (((byte2.toInt() and 255) shl 8) or (byte1.toInt() and 255))
}
Thanks,
Reza
To clarify: are you looking for an existing function in the Kotlin library that would do the same thing? (If yes, there's no such function)
rshah
March 6, 2014, 2:28am
3
Yes i was looking for function in Kotlin library.
Thanks for the clarification.
Recently, I needed such feature too. maybe we can ask for it in standard library.
Hi,
Byte.toUnsignedInt()
Byte.toUnsignedLong()
Int.toUnsignedLong()
Above functions are available in java 8 and would be nice to see them in Kotlin too.
They are quite handy when one wants to read the value without considering the sign byte.
elect
October 21, 2016, 8:08am
5
If interested, I wrote this small util for boxed unsigned types and unsigned operations on primitives
I’ve also create a small library which allows you to read/write unsigned values from/to ByteArray: GitHub - mvysny/kotlin-unsigned-jvm: Utilities for working with unsigned values in Kotlin/JVM