Scala bit Short

Viewed 115

In my console, when I try to check (0xFFFF.toShort).toBinaryString, it returns

(0xFFFF.toShort).toBinaryString
res1: String = 11111111111111111111111111111111

Shouldn't it return 1111111111111111, as in 16 1s? (16bits)

How do I fix this?

THanks

2 Answers

The bug is https://github.com/scala/bug/issues/10216 that the extension methods are only defined for int.

The workaround is to supply them yourself for byte and short, as shown here https://github.com/scala/scala/pull/8383/files

For example

scala> implicit class MyRichByte(val b: Byte) extends AnyVal {
     | def toBinaryString: String = java.lang.Integer.toBinaryString(java.lang.Byte.toUnsignedInt(b))
     | }
class MyRichByte

scala> (0xFFFF.toByte).toBinaryString
val res4: String = 11111111

In the REPL, use // print followed by tab (for tab completion) to see

scala> (0xFFFF.toShort).toBinaryString  //print
scala.Predef.intWrapper(65535.toShort.toInt).toBinaryString // : String

use ammonite desugar,

@ desugar((0xFFFF.toShort).toBinaryString)
res5: Desugared = scala.Predef.intWrapper(65535.toShort.toInt).toBinaryString

toBinaryString is a method of Int and there is an implicit conversion from Short to Int (intWrapper). and the toShort is convert to -1, and -1 in turn converted to Int -1 and that is how we get the 32 of "1".

Related