Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write binary literals in Scala?

Tags:

binary

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 ?.

like image 321
Lars Tackmann Avatar asked Sep 05 '25 17:09

Lars Tackmann


1 Answers

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
like image 161
Kim Stebel Avatar answered Sep 07 '25 18:09

Kim Stebel