Byte encapsulation in String
Due to restrictions on incoming data in my program, I need to take a byte array and encapsulate it in a string, meaning I need to do something like this (that doesn't break)
Byte[] byteArray = "Encapsulate";
String encap = (String) byteArray;
I need to preserve the byteArray data, but wrap it in a String.
Any help would be greatly appreciated, thanks!
Re: Byte encapsulation in String
The String class has a constructor that takes a byte array.
Can you give an example of what you want to do?
Give a byte array with some values and show what String you want to get.
Re: Byte encapsulation in String
This example code:
byte[] b = {116, 101};
String toString = byteToString(b);
System.out.println(toString);
Produces this:
"116101"
Where the "" is in place to show it is a string
Re: Byte encapsulation in String
That looks like you are converting the byte values as int values to their base 10 representation as a String.
Look at the Integer class's toString() method.
The trick will be for values < 100 (2 digits) and values < 10 (1 digit). They will have to be padded to get 3 digits.
Re: Byte encapsulation in String
As Norm mentioned, you might have a problem parsing the string . An alternative would be to convert the byte to its binary representation as a String (the Integer class has a toBinaryString() method to convert an int to a binary representation - take the least significant 8 chars). You can convert back using the Integer.parseInt method with the appropriate base