How to set specific bits in a char with Scala

1 Answer

0 votes
object BitManipulation {
  def printBinary(ch: Byte): Unit = {
    val binary = ch & 0xFF // Treat as unsigned
    println(String.format("%8s", Integer.toBinaryString(binary)).replace(' ', '0'))
  }

  def main(args: Array[String]): Unit = {
    // A Byte occupies 8 bits of memory and stores values ranging from -128 to 127
    var ch: Byte = 0 
    ch = (ch | (1 << 2)).toByte // Set the 7th bit
    ch = (ch | (1 << 4)).toByte // Set the 3rd bit

    printBinary(ch)             // Binary representation
    println(s"Value: $ch")      // Decimal value (may appear negative due to signed Byte)
  }
}



/*
run:
 
00010100
Value: 20
 
*/

 



answered Jul 31, 2025 by avibootz
...