scalabinary

How to write binary literals in Scala?


Scala has direct support for using hex and octal numbers:

scala> 01267 + 0100
res1: Int = 759

scala> 0x12AF + 0x100
res2: Int = 5039

but how do you do express an integer as a binary number in Scala ?.


Solution

  • If performance is not an issue, you can use a String and convert it to an integer.

    val x = Integer.parseInt("01010101", 2)
    

    Binary numbers aren't supported directly in part because you can easily convert from hexadecimal to binary and vice versa. To make your code clearer, you can put the binary number in a comment.

    val x = 0x55 //01010101