blue-sky - 1 month ago 6
Scala Question

How to xor char within string and add to List?

In this code where I'm attempting to xor the corresponding characters of two strings :

``````val s1 = "1c0111001f010100061a024b53535009181c";
val s2 = "686974207468652062756c6c277320657965";
val base64p1 = Base64.getEncoder().encodeToString(new BigInteger(s1, 16).toByteArray())
val base64p2 = Base64.getEncoder().encodeToString(new BigInteger(s2, 16).toByteArray())
val zs : IndexedSeq[(Char, Char)] = base64p1.zip(base64p2);
val xor = zs.foldLeft(List[Char]())((a: List[Char] , b: (Char, Char)) =>  ((Char)((b._1 ^ b._2))) :: a)
``````

produces error :

``````Char.type does not take parameters
[error]         val xor = zs.foldLeft(List[Char]())((a: List[Char] , b: (Char, Char)) =>  ((Char)((b._1 ^ b._2))) :: a)
``````

How to xor the corresponding string char values and add them to List ?

What you're doing is can be simplified.

``````val xor = base64p1.zip(base64p2).map{case (a,b) => (a^b).toChar}.reverse
``````

The result of the XOR op (`^`) is an `Int`. Just add `.toChar` to change it to a `Char` value.

But it looks like what you really want to do is XOR two large hex values that are represented as strings, and then return the result as a string. To do that all you need is...

``````val (v1, v2) = (BigInt(s1, 16), BigInt(s2, 16))
f"\${v1 ^ v2}%x"  // res0: String = 746865206b696420646f6e277420706c6179
``````