How to convert hex string to byte array in Scala?

Scala | Convert Hex String to Byte Array: Here, we will learn to convert a given hex string to byte array in Scala. We will learn about methods to convert.
Submitted by Shivang Yadav, on June 13, 2020

Hex String in Scala denotes value in hexadecimal number system i.e. base 16 number system.


hexString = "32AF1"

Byte Array is an array that stores elements of byte data type.

Converting Hex String to Byte Array

We can convert a hex string to a byte array in Scala using some method from java libraries which is valid as Scala uses the java libraries for most of its functions.


import scala.math.BigInt

object MyClass {
    def main(args: Array[String]) {
        val hexString = "080A4C";
        println("hexString : "+ hexString)
        val integerValue = Integer.parseInt(hexString, 16)
        val byteArray = BigInt(integerValue).toByteArray
        println("The byte Array for the given hexString is : ")
        for(i <- 0 to byteArray.length-1 )
            print(byteArray(i)+ " ")


hexString : 080A4C
The byte Array for the given hexString is : 
8 10 76 


In the above code, we have a hexadecimal string named hexString, and then convert it to integer value using parseInt() method of Integer class and stored the value to a variable named integerValue. We will convert this integer value to byteArray using the toByteArray method of BigInt class and store it to a variable named byteArray and printed the value using print() method.

Scala String Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.