Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifting and sign

Tags:

scala

Let me start with the problem:

  def word(byte1 : Byte, byte2 : Byte, byte3 : Byte, byte4: Byte) : Int = {
    ((byte4 << 0)) | ((byte3 << 8)) | ((byte2 << 16)) | ((byte1 << 24))
  }

The goal here is pretty simple. Given 4 bytes, pack them in to an Int.

The code above does not work because it appears the shift operator tries to preserve the sign. For example, this:

word(0xFA.toByte, 0xFB.toByte, 0xFC.toByte, 0xFD.toByte).formatted("%02X")

Produces FFFFFFFD when I would have expected FAFBFCFD.

Making the problem smaller:

0xFE.toByte << 8

Produces -2 in two's complement, not 0xFE00.

How can I do a shift without the sign issues?

like image 576
vcsjones Avatar asked Mar 09 '26 11:03

vcsjones


1 Answers

AND the bytes with 0xFF to undo the effects of sign extension before the shift:

((byte4 & 0xFF) << 0) | ((byte3 & 0xFF) << 8) | ...
like image 158
user2357112 supports Monica Avatar answered Mar 11 '26 15:03

user2357112 supports Monica