Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String to byte conversion issue

I have some test code which is not working as I expect, after reviewing various sites and specifications I still cannot figure out what is happening.

Here is my test code:

byte[] b = new byte[8];
b[0] = (byte)0x72;
b[1] = (byte)0x3A;
b[2] = (byte)0x60;
b[3] = (byte)0x01;
b[4] = (byte)0x0E;
b[5] = (byte)0x10;
b[6] = (byte)0x8A;
b[7] = (byte)0x11;
String bitmapStr = new String(b);
try {
    b = bitmapStr.getBytes("US-ASCII");
} catch (Exception ex) {
    ex.printStackTrace();
}
System.out.println("DEBUG: bitmapStr = \"" +bitmapStr + "\"");
for (int i=0; i<=7; i++) {
    int byte1 = b[i];
    System.out.println("byte"+i + ": " + Integer.toHexString(byte1));
}

When I run the program I get the following in the console output:

DEBUG: bitmapStr = "r:`�"
byte0: 72
byte1: 3a
byte2: 60
byte3: 1
byte4: e
byte5: 10
byte6: 3f
byte7: 11

See how byte6 i.e. b[6] from my byte array outputs 0x3F, but it should be 0x8A.

Any ideas why?

By the way, if I use UTF-8 encoding I get an even more funky output (although ASCII is correct).

UTF-8 String encoding output:

byte0: 72
byte1: 3a
byte2: 60
byte3: 1
byte4: e
byte5: 10
byte6: ffffffef
byte7: ffffffbf
like image 201
Steve Avatar asked Feb 06 '26 01:02

Steve


2 Answers

Try another form of the String constructor:

String bitmapStr = new String(b,"ISO-8859-1");
like image 56
Chris Gerken Avatar answered Feb 08 '26 15:02

Chris Gerken


Try something like this to change a string to byte:-

  String source = "2675326";
 byte[] byteArray = source.getBytes("UTF-16LE");

or change your code to:-

 String bitmapStr = new String(b,"US-ASCII");
like image 25
Rahul Tripathi Avatar answered Feb 08 '26 13:02

Rahul Tripathi