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
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
There was a proposal to include new data types for unsigned Int in scala, but it 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/unsigned-integers.html
You may also refer Unsigned variables in Scala.
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
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>