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.

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.

Program:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.