×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to convert hex string to byte array in Scala?

By IncludeHelp Last updated : October 20, 2024

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

Example:

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.

Scala Program for Converting Hex String to Byte Array

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)+ " ")
    }
}

Output

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

Description

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 www.includehelp.com. All rights reserved.