如何在 Scala 中编写二进制文字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7197119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 03:23:35  来源:igfitidea点击:

How to write binary literals in Scala?

scalabinary

提问by Lars Tackmann

Scala has direct support for using hex and octal numbers:

Scala 直接支持使用十六进制和八进制数:

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

但是如何在 Scala 中将整数表示为二进制数?

回答by Kim Stebel

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

回答by Eugene Burmako

In 2.10 you can create a string interpolator for that, e.g. it's possible to write b"0010"to mean 2. Using macros you can get rid of associated runtime overhead and do the conversion at compile-time. Take a look at Jason Zaugg's macrocosmto see it in action:

在 2.10 中,您可以为此创建一个字符串插值器,例如可以写入b"0010"mean 2。使用宏,您可以摆脱相关的运行时开销并在编译时进行转换。看看 Jason Zaugg 的宏观世界,看看它在行动:

scala> b"101010"
res4: Int = 42

scala> b"102"
<console>:11: error: exception during macro expansion: invalid binary literal
              b"102"
              ^

回答by AmigoNico

Using the new "implicit class" and "value class" mechanisms in 2.10, you can write something like this to add convenience methods without the overhead of object creation:

使用 2.10 中新的“隐式类”和“值类”机制,您可以编写类似这样的东西来添加方便的方法,而无需创建对象的开销:

implicit class IntToBase( val digits:String ) extends AnyVal {
  def base(b:Int) = Integer.parseInt( digits, b )
  def b = base(2)
  def o = base(8)
  def x = base(16)
}

That allows you to do things like

这允许你做这样的事情

"555".o  // 365 decimal

and no IntToBase object is ever actually created.

并且实际上从未创建过 IntToBase 对象。

回答by Luigi Plinge

You would need to be careful if you're converting from an integer that "looks like" binary as @agilesteel suggests. For example 0101.bwould try to convert 65 decimal to binary (initial 0 signifying octal), whereas 101.bwould try to convert 101 decimal to binary. It only really makes sense to try to convert from a String, for which there is Integer.parseInt, and from a number to the binary String representation, for which there is Integer.toString(x, 2).

如果您从@agilesteel 建议的“看起来像”二进制的整数进行转换,则需要小心。例如,0101.b将尝试将十进制 65 转换为二进制(初始 0 表示八进制),而101.b尝试将十进制 101 转换为二进制。尝试从存在 的字符串Integer.parseInt以及从数字转换为存在的二进制字符串表示形式才真正有意义Integer.toString(x, 2)

I can't think of too many use-cases for programmatic binary literals. That said, they've made it to Java 7as a number with prefix 0b, so I'd be surprised if they didn't appear in Scala soon. Java seems to have done fine without them for 15 years though.

我想不出太多编程二进制文字的用例。也就是说,他们已经作为一个带有前缀的数字进入了 Java 70b,所以如果他们没有很快出现在 Scala 中,我会感到惊讶。15 年来,Java 似乎在没有它们的情况下做得很好。

回答by agilesteel

If you are planning on using it a lot you can simulate the behavior with an implicit conversion.

如果您打算大量使用它,则可以通过隐式转换来模拟行为。

object Extensions {
  implicit def conversion(x: Int) = new BinaryInt(x)
  class BinaryInt(x: Int) {
    def b = {
      // Conversion code like Integer.parseInt
      // as Kim suggested
    }
  }
}

Now you can do stuff like

现在你可以做类似的事情

import Extensions._
val x = 0101.b
// or
val x = 5.b

You have to decide for yourself, which direction the conversion should go.

您必须自己决定转换应该朝哪个方向发展。

回答by ehrt1974

If you want to get a string of the binary representation of an Int you can call 4.toBinaryString. Padding is more difficult. You'll have to do something like: 4.toBinaryString.reverse.padTo(8, "0").reverse.mkString

如果你想获得一个 Int 的二进制表示的字符串,你可以调用4.toBinaryString. 填充更困难。您必须执行以下操作:4.toBinaryString.reverse.padTo(8, "0").reverse.mkString

回答by Babofett

def _0b(row: Int): Int = {
  row.toString
    .reverse
    .split("")
    .zipWithIndex
    .map(x => (x._1.toInt, x._2))
    .filter(_._1 == 1)
    .map(x => Math.pow(2,x._2).toInt)
    .sum
}

_0b(10011001) = 153

Though it is limited to 32Bit Values

虽然它仅限于 32Bit 值