Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Java String to an ASCII byte array?

How to convert a Java String to an ASCII byte array?

like image 919
farm ostrich Avatar asked Apr 16 '11 16:04

farm ostrich


People also ask

How do I encode a Java string as ASCII?

Convert String to ASCII 2.1 We can use String. getBytes(StandardCharsets. US_ASCII) to convert the string into a byte arrays byte[] , and upcast the byte to int to get the ASCII value. 2.2 Java 9, there is a new API String.

Can we convert string to byte array in Java?

A String is stored as an array of Unicode characters in Java. To convert it to a byte array, we translate the sequence of characters into a sequence of bytes. For this translation, we use an instance of Charset. This class specifies a mapping between a sequence of chars and a sequence of bytes.

How do I convert to ASCII?

You must first convert the character to its ASCII value. In LiveCode, this is done with the charToNum function. Converting a number to the corresponding character is done with the numToChar function. The first of these statements converts a number to a character; the second converts a character to its ASCII value.


1 Answers

Using the getBytes method, giving it the appropriate Charset (or Charset name).

Example:

String s = "Hello, there."; byte[] b = s.getBytes(StandardCharsets.US_ASCII); 

If more control is required (such as throwing an exception when a character outside the 7 bit US-ASCII is encountered) then CharsetDecoder can be used:

private static byte[] strictStringToBytes(String s, Charset charset) throws CharacterCodingException {     ByteBuffer x  = charset.newEncoder().onMalformedInput(CodingErrorAction.REPORT).encode(CharBuffer.wrap(s));     byte[] b = new byte[x.remaining()];     x.get(b);     return b;  } 

Before Java 7 it is possible to use: byte[] b = s.getBytes("US-ASCII");. The enum StandardCharsets, the encoder as well as the specialized getBytes(Charset) methods have been introduced in Java 7.

like image 143
Sebastian Paaske Tørholm Avatar answered Sep 23 '22 15:09

Sebastian Paaske Tørholm