Home » Core Java » lang » String » Convert String to byte array ASCII encoding

About Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.

Convert String to byte array ASCII encoding

This is an example of how to convert a String to byte array with ASCII encoding. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Converting a String to byte array with ASCII encoding implies that you should:

  • Create a String.
  • Create a byte array with size equal to the String length.
  • For every position in the byte array use the charAt(int index) API method of String to get the char value at the specified index of the String and put it in the byte array.

Let’s take a look at the code snippet that follows:

public static byte[] stringToBytesASCII(String str) {
 byte[] b = new byte[str.length()];
 for (int i = 0; i < b.length; i++) {
  b[i] = (byte) str.charAt(i);
 }
 return b;
}

Using the resulted byte array we can convert back to the original String, by utilizing the “classic” String constructor “new String(byte[])

 
This was an example of how to convert a String to byte array with ASCII encoding in Java.

Related Article:

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments