Reputation:
I want to convert the following hash "d41d8cd98f00b204e9800998ecf8427e" to binary string. However, I can't seem to find a way to do that? Can someone teach me how I can do it in Scala? Thanks
Upvotes: 1
Views: 3766
Reputation: 33019
Use BigInt
:
scala> BigInt("d41d8cd98f00b204e9800998ecf8427e", 16).toString(2)
res0: String = 11010100000111011000110011011001100011110000000010110010000001001110100110000000000010011001100011101100111110000100001001111110
The 16
above means the string should be parsed in hex (base 16), and the 2
means the output string should be in binary (base 2).
If you want to dump the raw binary out to a file, you can convert the BigInt
to a byte array and dump that:
scala> BigInt("d41d8cd98f00b204e9800998ecf8427e", 16).toByteArray
res1: Array[Byte] = Array(0, -44, 29, -116, -39, -113, 0, -78, 4, -23, -128, 9, -104, -20, -8, 66, 126)
Note that this gives you back 17 bytes instead of the 16 you'd expect for a 128-bit hash. That's because BigInt is a signed value, so it pads the byte array with an extra 0
in the most-significant-byte place to keep the value from being interpreted as negative. You could use res1.takeRight(16)
to grab only the 16 bytes you're probably interested in.
Upvotes: 6