1

How do I convert a byte array to a String in BlackBerry?

I have used

new String(bytearray,encoding type);

I am getting [B@fb5955d6 when calling toString().Can anyone help get this string in a readable format for BlackBerry?

user1213202
  • 1,305
  • 11
  • 23
  • http://stackoverflow.com/questions/6684665/java-byte-array-to-string-to-byte-array – Rince Thomas Feb 19 '13 at 05:55
  • 3
    **How** are you seeing the value `[B@fb5955d6` for your byte array? Are you looking at it in the debugger? Printing it out? Please show some of the code you have tried to use. If you tried `new String(byte[], encoding), *which* encoding did you use? – Nate Feb 19 '13 at 05:55

2 Answers2

2

You don't show us where this byte data is coming from, or what value you expect it to have. So, I'm not sure I can fully debug your problem. But, hopefully this helps:

The reason you are seeing [B@fb5955d6 printed out when you simply call toString() on your byte array is that the default implementation of toString() will just print out a short code for the array data type (e.g. byte), and then something like an address (if you're familiar with C/C++) of your variable, which is almost never what you really want, especially in Java.

When you have binary data (as a byte[]), Java doesn't know whether you intend that data to be a String, or a ButtonField, or a FuzzyWarble. So, it has nothing more meaningful to print out than the object's address.

If you want to print out String data, you need to create a String object with the byte[], but to do that, you need to either use the default character encoding, or specify which encoding you want. "UTF-8" and "ASCII" are two popular encodings.

If I run this code

  try {         
     byte[] bytes = new byte[] { 100, 67, 126, 35, 53, 42, 56, 126, 122 };
     System.out.println("bytes are " + bytes.toString());
     String s = new String(bytes, "UTF-8");
     System.out.println("string is " + s);
  } catch (UnsupportedEncodingException e1) {
  }

I see this

bytes are [B@3b50e2ee
string is dC~#5*8~z

As you see, the address I see is different from the one you see (because I'm running on a different machine, with different memory layout). But, when converted to a String with "UTF-8" encoding, I see the value that you see.

So, maybe that's the right value?

Again, we don't know where the binary data comes from, or what it's supposed to be, but I can tell you that the code above is a typical way to convert byte arrays to strings.

Community
  • 1
  • 1
Nate
  • 31,017
  • 13
  • 83
  • 207
0

Try this -

byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};

String value = new String(byteArray);

This will give you the value 'WOW..'

Rince Thomas
  • 4,158
  • 5
  • 25
  • 44