Unsigned integer in scala

只谈情不闲聊 提交于 2020-01-03 05:22:31

问题


I have a requirement to store only positive values. As I understand, signed can store both positive and negative values. Are there any unsigned integer, double data types in Scala?

Regards


回答1:


There was a proposal to include new data types for unsigned Int in scala, but if was going to have a performance impact. Hence the people who maintain scala decided not to go ahead with the proposal of an unsigned Int in scala.

Please refer the following https://docs.scala-lang.org/sips/rejected/unsigned-integers.html for complete details.

You may also refer Unsigned variables in Scala.




回答2:


Scala doesn't own unsigned int but you can use spire library, they have UByte, UShort, UInt, and ULong etc. Please have a look here https://github.com/non/spire/blob/master/GUIDE.md




回答3:


Scala doesn't support Unsigned integers, but you can have a workaround like this.

scala> val x = 2147483647
x: Int = 2147483647

scala> val y = x+4
y: Int = -2147483645

Here you want to have the value of y as 2147483651 instead of the negative value limited by the Integer type. To get the positive value, you can use the BigInt library. Get the byte sequence of the Integer Value and prefix it with another "zero", so that the entire value now becomes positive.

scala> import scala.math.BigInt
import scala.math.BigInt

scala> val prefix:Array[Byte]=Array(0)
prefix: Array[Byte] = Array(0)

scala> val y = BigInt(prefix ++ BigInt(x+4).toByteArray)
y: scala.math.BigInt = 2147483651

scala>

You can wrap it as a function like this

scala> def unsignedInt(a:Integer):scala.math.BigInt=
     | {
     |  val prefix:Array[Byte]=Array(0)
     |  BigInt(prefix ++ BigInt(a).toByteArray)
     | }
unsignedInt: (a: Integer)scala.math.BigInt

scala> unsignedInt(x)+unsignedInt(4)
res31: scala.math.BigInt = 2147483651

scala>


来源:https://stackoverflow.com/questions/53088633/unsigned-integer-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!