CharBuffer

Convert String to byte array UTF encoding

With this example we are going to demonstrate how to convert a String to byte array and vice-versa using the default character encoding in Java. In short, to perform the aforementioned conversion, we are going to use classes from the NIO package in Java so as to convert every character from the target String to its byte equivalent. Namely we :

  • Use the toCharArray() API method of the String class to get its char array equivalent. Every character in Java is represented as a fixed-width 16-bit entity
  • We construct an empty byte array to hold the bytes for each character of the target String – the size of the byte array should be double the size of the character array
  • We use Java NIO package ByteBuffer class to wrap the newly created byte array and we dictate by using the asCharBuffer() API method that we are going to use the specific ByteBuffer as CharBuffer
  • Last but not least we insert all characters from the character array to the CharBuffer and thus to the proxied byte array

as shown in the code snippets below.

public static byte[] stringToBytesUTFNIO(String str) {
 char[] buffer = str.toCharArray();
 byte[] b = new byte[buffer.length << 1];
 CharBuffer cBuffer = ByteBuffer.wrap(b).asCharBuffer();
 for(int i = 0; i < buffer.length; i++)
  cBuffer.put(buffer[i]);
 return b;
}
public static String bytesToStringUTFNIO(byte[] bytes) {
 CharBuffer cBuffer = ByteBuffer.wrap(bytes).asCharBuffer();
 return cBuffer.toString();
}

This was an example of how to convert a String to byte array 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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button