I'm trying to develop an Android app, where I need to add an byte value (8-bit) inside a string and read it back again in byte[].
However I'm getting some different value when I convert the string to byte[] again using getBytes(). I think its some encoding or charset issue.
BTW I'm new to java programming I mostly code in C.
Code:
void function(void)
{
String a = "bla";
char x = (0xD0 & 0xFF); //Need to add & read back '0xD0'
a += x;
Log.d(TAG,"TEST: "+a);
String mm = "-- ";
byte[] buffer = null;
try {
buffer = a.getBytes("US-ASCII");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
}
for (int i = 0; i < buffer.length; i++) {
mm+=" "+Integer.toHexString( buffer[i] );
}
Log.e(TAG, "Len:"+buffer.length+mm);
}
Output:
TEST: bla
Len:4-- 62 6c 61 3f
Expected:
Len:4-- 62 6c 61 d0
Found the solution:
Now I'm using encoding UTF-16LE, which does not loose data, and transmitting even bytes, skip odd bytes
Solution:
void function(void)
{
String a = "bla";
char x = 0xD0;
a += x;
Log.d(TAG,"TEST: "+a);
String mm = "-- ";
byte[] buffer = null;
try {
buffer = a.getBytes("UTF-16LE");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
}
for (int i = 0; i < buffer.length; ) {
mm += i +":"+Integer.toHexString( buffer[i] ) + ",";
/* Skip odd bytes as using "UTF-16LE" encoding */
i+=2;
}
Log.e(TAG, "Len:"+buffer.length+mm);
}
Result:
Len:8-- 0:62,2:6c,4:61,6:ffffffd0,
bytes are signed -128 to 127,chars are positive 0 to 65535. You are probably addingchar0xFFD0 to yourString, due to sign extension.(byte)xgivesLen:6-- 62 6c 61 2d 34 38, and byanding with 0xff i am converting it to unsigned. I'm not getting how3fis getting there.bytetochargives same resultByteBufferor similar structure. JSYK: Your buffer result62 6c 61 2d 34 38is"bla-48"... the byte was converted to a string and appended.