How to convert hex string to int in Scala?

Scala | Conversion from hex string to int: Here, we are going to learn how to convert hex string to int in Scala with examples?
Submitted by Shivang Yadav, on May 23, 2020 [Last updated : March 10, 2023]

The hex string is also known as Hexadecimal Number String is a number created using hexadecimal number system i.e. base 16 number system. 

Integer in Scala is a numerical value that uses base 10 values.

Scala – Converting Hex String to Int

A hexadecimal string can be converted to integer type using the parseInt() method of the Integer class that will parse the given string with a given base to an integer value.

Syntax

    val int_value = Integer.parseInt(hex_string , base)

Program to convert hex string to int in Scala

object MyObject {
    def convertHexStringToInt(hexString : String): Int = {
        return Integer.parseInt(hexString, 16)
    }
    
    def main(args: Array[String]) {
        val hexString : String = "10DEA"
        println("The Hex String is " + hexString)
        println("The String converted to decimal is " + convertHexStringToInt(hexString))
    }
}

Output

The Hex String is 10DEA
The String converted to decimal is 69098

Explanation

In the above code, we have created a function convertHexStringToInt() which will convert the given hex String to an int. The convert uses the parseInt() method which is available in the Integer class. The function takes a string as a parameter and returns the integer which is string conversion of hexString. This returned value is printed using the println method.

Scala String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.