Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

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
...