UTF-16 to ASCII conversion in Java

后端 未结 4 603
花落未央
花落未央 2020-12-09 13:41

Having ignored it all this time, I am currently forcing myself to learn more about unicode in Java. There is an exercise I need to do about converting a UTF-16 string to 8-

4条回答
  •  余生分开走
    2020-12-09 14:32

    You can use java.nio for an easy solution:

    // first encode the utf-16 string as a ByteBuffer
    ByteBuffer bb = Charset.forName("utf-16").encode(CharBuffer.wrap(utf16str));
    // then decode those bytes as US-ASCII
    CharBuffer ascii = Charset.forName("US-ASCII").decode(bb);

提交回复
热议问题