How to convert a string to byte array in Scala?

Scala | Converting string to byte array: Here, we are going to learn how to convert a given string to byte array in Scala programming language?
Submitted by Shivang Yadav, on May 21, 2020

String in Scala is a sequence of characters. And, Byte Array in Scala is an array that stores a collection of binary data.

String to byte Array Conversion

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

Syntax:

    string.getBytes()

This will return a byte array.

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 :[[email protected]

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.







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.