How to convert a Java String to an ASCII byte array?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With