Byte to unsigned short conversion


#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


#2

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)


#3

Yes i was looking for function in Kotlin library. Thanks for the clarification.


#4

Recently, I needed such feature too. maybe we can ask for it in standard library.


#5

If interested, I wrote this small util for boxed unsigned types and unsigned operations on primitives