manonmars manonmars - 19 days ago 5
Scala Question

Scala: How do I extract the first secound third and fourth byte from an integer using bit operators to binary and back?

For example

-1234567890 = 10110110 01101001 11111101 00101110

10110110 = 182

01101001 = 105

11111101 = 253

00101110 = 46

I dont get how this should work. Thanks in advance!

Answer

This can be done exactly like in any other language, with bit shifts:

scala> val x = -1234567890
x: Int = -1234567890

scala> x & 0xFF
res0: Int = 46

scala> (x >> 8) & 0xFF
res1: Int = 253

scala> (x >> 16) & 0xFF
res2: Int = 105

scala> (x >> 24) & 0xFF
res3: Int = 182

Basically, you shift the value by the desired number of bytes to the right and then apply the mask to leave only the last byte:

0x000000FF == 0b00000000000000000000000011111111