Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a code point to UTF-8 byte array in Java

Tags:

java

utf-8

I need to convert a code point (supplied as an integer) to a UTF-8 byte array (probably represented as a ByteArrayOutputStream, unless there is a more efficient representation). A previous question asked how to do that by translating the algorithm to handwritten code, which of course would be an option, but given that the Java standard library already has the means to do it, best practice would be to try to use the standard library rather than duplicate the functionality.

I know of one way to do it: StringBuilder appendCodePoint followed by toString to convert the code point to a string, then getBytes to convert to a byte array, which can then be appended to the byte output stream, for ultimate gathering up into a larger composite byte array.

However, it feels like there should be a more elegant and efficient way, involving fewer steps.

What is the idiomatic way to do this in Java?

like image 257
rwallace Avatar asked Sep 25 '26 21:09

rwallace


1 Answers

The most compact form I can think of is this:

static byte[] utf8BytesForCodePoint(int codePoint) {
    return Character.toString(codePoint).getBytes(StandardCharsets.UTF_8);
}

This avoids the extra steps of creating a StringBuilder by using Character.toString(int codePoint).

like image 118
Joachim Sauer Avatar answered Sep 28 '26 10:09

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!