Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-16 to ASCII conversion in Java

Tags:

java

ascii

utf-16

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-bit ASCII. Can someone please enlighten me how to do this in Java? I understand that you can't represent all possible unicode values in ASCII, so in this case I want a code which exceeds 0xFF to be merely added anyway (bad data should also just be added silently).

Thanks!

like image 741
His Avatar asked Nov 28 '22 19:11

His


1 Answers

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);
like image 134
Gunslinger47 Avatar answered Dec 04 '22 22:12

Gunslinger47