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 XOR byte arrays in Scala

1 Answer

0 votes
object XORBytesDemo {

  def xorBytes(a: Array[Byte], b: Array[Byte]): Array[Byte] = {
    (a zip b).map { case (x, y) => (x ^ y).toByte }
  }

  def printBitsetArray(label: String, array: Array[Byte]): Unit = {
    print(s"$label: ")
    array.foreach { b =>
      val binary = (b & 0xFF).toBinaryString.reverse.padTo(8, '0').reverse
      print(s"$binary ")
    }    
    println()
  }

  def main(args: Array[String]): Unit = {
    val a = "Aragorn".getBytes("US-ASCII")
    val b = "Boromir".getBytes("US-ASCII")
    val c = xorBytes(a, b)

    printBitsetArray("a", a)
    printBitsetArray("b", b)
    printBitsetArray("c", c)

    print("c: ")
    c.foreach(b => print(s"${b & 0xFF} "))
  }
}
 
 
  
/*
run:
 
a: 01000001 01110010 01100001 01100111 01101111 01110010 01101110 
b: 01000010 01101111 01110010 01101111 01101101 01101001 01110010 
c: 00000011 00011101 00010011 00001000 00000010 00011011 00011100 
c: 3 29 19 8 2 27 28 
 
*/

 



answered Jul 12, 2025 by avibootz

Related questions

1 answer 68 views
68 views asked Jul 11, 2025 by avibootz
1 answer 65 views
65 views asked Jul 12, 2025 by avibootz
1 answer 93 views
1 answer 70 views
70 views asked Jul 12, 2025 by avibootz
1 answer 73 views
73 views asked Jul 12, 2025 by avibootz
1 answer 77 views
...