How to convert a Java String to an ASCII byte array?
Using the Example:
|
|||||||||
|
The problem with other proposed solutions is that they will either drop characters that cannot be directly mapped to ASCII, or replace them with a marker character like You might desire to have for example accented characters converted to that same character without the accent. There are a couple of tricks to do this (including building a static mapping table yourself or leveraging existing 'normalization' defined for unicode), but those methods are far from complete. Your best bet is using the junidecode library, which cannot be complete either but incorporates a lot of experience in the most sane way of transliterating Unicode to ASCII. |
|||
|
If you are a guava user there is a handy
Apart from not hard-coding arbitrary charset name in your source code it has a much bigger advantage: In Java 7 there is equivalent |
||||
|
There is only one character wrong in the code you tried:
Notice the upper case "String". This tries to invoke a static method on the string class, which does not exist. Instead you need to invoke the method on your string instance:
|
|||
|
If you happen to need this in Android and want to make it work with anything older than FroYo, you can also use EncodingUtils.getAsciiBytes():
|
|||
|
Convert string to ascii values.
|
|||
|
Try this:
|
||||
|