I need some help converting a java byte array to a 7-Bit ASCII string. However I am getting 8-bit sequences and need to escape any unreadable character to it’s escaped sequence. Is there a simple solution for this or do I need to build my own?
Seeing that the range of readable characters in 7-bit ASCII is continuous right now I am thinking of the following:
for( int i = 0; i < buffer.length; i++ ) {
int codePoint = ( (int) buffer[ i ] ) & 255;
if( 0x20 <= codePoint && codePoint <= 0x7e ) {
res = res + String( (char) codePoint );
} else {
String c = Integer.toHexString( codePoint );
if( c.length() < 2 ) {
c = "0" + c;
}
res = res + "\\0x" + c;
}
}
However this seems like an awful lot of work for such a simple conversion. Is there a better way?
Also I might need to do the same to data that has been converted from the byte array to strings. Is there a simpler solution in this case?
You can use the format method to pare back the verbiage.
Note that this method is only safe because the ASCII range matches the lower range of the UTF-16 encoding used by Java Strings.