Ninjoe Quah
Ninjoe Quah

Reputation: 399

Java - String of bytes to bytes[]

I have a

String b = "[B@64964f8e";

this is the byte[] output which i store in a string

Now I would like to convert it back to byte[]

byte[] c = b.getBytes();

but it gave me different byte which is

[B@9615a1f

how can I get back the same as [B@64964f8e ?

Upvotes: 0

Views: 217

Answers (4)

Tim S.
Tim S.

Reputation: 56536

"[B@64964f8e" is not a string encoding of your byte[]. That is the result of the default toString() implementation, which tells you the type and reference location. Maybe you wanted to use base64-encoding instead, e.g. using javax.xml.bind.DatatypeConverter's parseBase64Binary() and printBase64Binary():

byte[] myByteArray = // something
String myString = javax.xml.bind.DatatypeConverter.printBase64Binary(myByteArray);
byte[] decoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(myString);
// myByteArray and decoded have the same contents!

Upvotes: 1

rocketboy
rocketboy

Reputation: 9741

A simple answer is:

System.out.println(c) prints the reference's representation of c object. Not c's content.(Only in cases where Object's toString() method is not overriden)

    String b = "[B@64964f8e";
    byte[] c = b.getBytes();

    System.out.println(c);             //prints reference's representation of c
    System.out.println(new String(c)); //prints [B@64964f8e

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533472

I suspect you are trying to do the wrong thing and this won't help you at all because I would have though you want the contents to be the same, not the result of the toString() method.

You shouldn't be using a text String to binary data but you can use ISO-8859-1

byte[] bytes = random bytes
String text = new String(bytes, "ISO-8859-1");
byte[] bytes2 = text.getBytes("ISO-8859-1"); // gets back the same bytes.

But to answer your question, you can do this.

Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);
byte[] bytes = new byte[0];
unsafe.putInt(bytes, 1L, 0x64964f8e);
System.out.println(bytes);  

prints

[B@64964f8e

Upvotes: 1

nanofarad
nanofarad

Reputation: 41271

String b = "[B@64964f8e";

that's not a real string. That's the type and address of your byte array. It's nothing more than a transient reference code, and if the original array was GC'd you wouldn't even have a hope of getting it back with really funky native methods romping through memory.

Upvotes: 1

Related Questions