Formatting binary values in Scala

2020-02-03 05:04发布

Does Scala have a built in formatter for binary data?

For example to print out: 00000011 for the Int value 3.

Writing one won't be difficult - just curious if it exists.

8条回答
等我变得足够好
2楼-- · 2020-02-03 05:42

Here is one more way (old Java):

val x = 5
val str = Integer.toString(x,2)

Just like Lauri answer, it doesn't print leading zeros.

查看更多
贼婆χ
3楼-- · 2020-02-03 05:49
scala> 3.toBinaryString
res0: String = 11

Scala has an implicit conversion from Int to RichInt which has a method toBinaryString. This function does not print the leading zeroes though.

查看更多
贼婆χ
4楼-- · 2020-02-03 05:49

I don't know of a direct API method to do it, but here is one way of doing it:

def toBinary(i: Int, digits: Int = 8) =
    String.format("%" + digits + "s", i.toBinaryString).replace(' ', '0')
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-02-03 05:49

8 digits for number 3 with leading zeros:

printf ("%08d", 3.toBinaryString.toInt)
00000011

Since Hosam Aly suggests to create a String as well, here is a method to do so:

def asNdigitBinary (source: Int, digits: Int): String = {
  val l: java.lang.Long = source.toBinaryString.toLong
  String.format ("%0" + digits + "d", l) }

In the general case, using a Long is more appropriate, since binary values get long very fast:

scala> asNdigitBinary (1024*512-1, 32)
res23: String = 00000000000001111111111111111111

So keep that in mind - a selfmade, recursive approach which generates digit by digit and fills them up in the end would be easily made to handle arbitrary values of BigInt.

def toBinDigits (bi: BigInt): String = { 
  if (bi == 0) "0" else toBinDigits (bi /2) + (bi % 2)}

def fillBinary (bi: BigInt, len: Int) = { 
  val s = toBinDigits (bi)
  if (s.length >= len) s 
  else (List.fill (len-s.length) ("0")).mkString ("") + s
}

It would be nice, if

def asNdigitBinary (source: Int, digits: Int): String = {
  val l = BigInt (source.toBinaryString.toLong) 
  String.format ("%0" + digits + "d", l)}

would work, but "%0Nd" does not match for BigInt digits. Maybe a Bugreport/Feature request should be made? But to Scala or Java?

查看更多
劫难
6楼-- · 2020-02-03 05:49

You can do something like this:

scala> val x = 3
x: Int = 3

scala> Integer.toString(x, 2)
res4: java.lang.String = 11

As with other suggestions, this doesn't have leading zeros...

查看更多
来,给爷笑一个
7楼-- · 2020-02-03 05:50

I usually use to prepend zeroes of the wanted length -1 and then just chop the rightmost characters:

"0000000" + 3.toBinaryString takeRight 8

This works fine for negative values as well.

查看更多
登录 后发表回答