0

I have a unsigned data representation like this:

val str = "145 38 0 255 0 1"

I want to now get this unsigned representation as a byteString after which I can manipulate on the individual bits to extract information. So basically what I want is to get the unsigned version.

For example., the unsigned binary representation of 145 is 10010001, but the signed version is -00000111.

scala> 145.byteValue
res128: Byte = -111 // I would need an unsigned value instead!

So is there a function or an approach to convert the 145 to an unsigned representation?

joesan
  • 13,963
  • 27
  • 95
  • 232
  • IMHO Unsigned integers are not possible Scala. There was a scala SIP for that which was rejected. Please refer my earlier answer https://stackoverflow.com/a/53088716/7803797 – Chaitanya Jul 18 '19 at 11:34

1 Answers1

1

Signed and unsigned bytes (or Ints or Longs) are just two different ways to interpret the same binary bits. In signed bytes the first bit from the left (most significant bit) is interpreted as the sign.

0 means positive, 1 means negative.

For negative numbers, what comes after the minus sign is 256 - unsigned-value. So in your case what we get is 256 - 145 = 111.

Java / Scala bitwise operators work on the underlying bits, not on the signed/unsigned representation, but of course the results, when printed are still interpreted as signed.

Actually, to save on confusion, I would just work with Ints (or Shorts). But it will work just as well with bytes.

For example to get the n-th bit you could do something like:


def bitValue(byte: Byte, n: Byte) = {
    val pow2 = Math.pow(2, n - 1).toInt
    if((pow2 & byte) == 0) 0
    else 1
}

bitValue(145.byteValue, 8)
res27: Int = 1