String

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:

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.
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
Back to top button