Q:

How to convert a string to byte array in Scala?

belongs to collection: Scala String Programs

0

We can convert a string to byte array in Scala using getBytes() method.

Syntax:

    string.getBytes()

This will return a byte array.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to convert string to byte Array

Program 1:

// Program to convert string to Byte Array 
object MyClass {
    
    def main(args: Array[String]) {
        val string : String = "IncludeHelp"
        println("String : " + string)
        // Converting String to byte Array 
        // using getBytes method 
        val byteArray = string.getBytes
        println("Byte Array :" + byteArray)
    }
    
}

Output:

String : IncludeHelp
Byte Array :[B@fac80

Explanation:

In the above code, we have used the getBytes method to convert the string to byte array and then printed the byteArray using the println() method which gives the pointer value.

Program 2:

// Program to convert string to Byte Array 
object MyClass {
    
    def main(args: Array[String]) {
        val string : String = "IncludeHelp"
        println("String : " + string)

        // Converting String to byte Array 
        // using getBytes method 
        val byteArray = string.getBytes

        // printing each value of the byte Array 
        println("Byte Array : ")
        for(i <- 0 to byteArray.length-1)
        print(byteArray(i) + "   ")
    }
    
}

Output:

String : IncludeHelp
Byte Array : 
73   110   99   108   117   100   101   72   101   108   112

Explanation:

In the above code, we have created a String named string with value "IncludeHelp" and then used the getBytes to convert it into a byte Array then printed the elements of the array using for loop.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to convert byte array to string in Scala?... >>
<< Extracting difference, intersection, and distinct ...