Is there a neat way in Scala to convert a hexadecimally encoded String
to a protobuf ByteString
(and back again)?
We can convert a hex string to byte array in Java by first converting the hexadecimal number to integer value using the parseInt() method of the Integer class in java. This will return an integer value which will be the decimal conversion of hexadecimal value.
As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.
A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..
You can use (without additional dependencies) DatatypeConverter
as:
import com.google.protobuf.ByteString
import javax.xml.bind.DatatypeConverter
val hexString: String = "87C2D268483583714CD5"
val byteString: ByteString = ByteString.copyFrom(
DatatypeConverter.parseHexBinary(hexString)
)
val originalString = DatatypeConverter.printHexBinary(byteString.toByteArray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With