Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala hex string to bytes

Is there a neat way in Scala to convert a hexadecimally encoded String to a protobuf ByteString (and back again)?

like image 523
Max Power Avatar asked Nov 02 '17 08:11

Max Power


People also ask

How do you convert hex to bytes?

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.

Is hex a 1 byte?

As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.

What is byte array?

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


1 Answers

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)
like image 76
Federico Pellegatta Avatar answered Oct 06 '22 08:10

Federico Pellegatta