Reputation: 4201
This is simply to error check my code, but I would like to convert a single byte out of a byte array to a string. Does anyone know how to do this? This is what I have so far:
recBuf = read( 5 );
Log.i( TAG, (String)recBuf[0] );
But of course this doesn't work.
I have googled around a bit but have only found ways to convert an entire byte[] array to a string...
new String( recBuf );
I know I could just do that, and then sift through the string, but it would make my task easier if I knew how to operate this way.
Upvotes: 7
Views: 15524
Reputation: 842
You're assuming that you're using 8bit character encoding (like ASCII) and this would be wrong for many others.
But with your assumption you might just as well using simple cast to character like
char yourChar = (char) yourByte;
or if really need String:
String string = String.valueOf((char)yourByte);
Upvotes: 0
Reputation: 7899
Use toString
method of Byte
String s=Byte.toString(recBuf[0] );
Try above , it works.
Example:
byte b=14;
String s=Byte.toString(b );
System.out.println("String value="+ s);
Output:
String value=14
Upvotes: 9
Reputation: 68177
Another alternate could be converting byte
to char
and finally string
Log.i(TAG, Character.toString((char) recBuf[0]));
Or
Log.i(TAG, String.valueOf((char) recBuf[0]));
Upvotes: 0
Reputation: 6783
There's a String
constructor of the form String(byte[] bytes, int offset, int length)
. You can always use that for your conversion.
So, for example:
byte[] bite = new byte[]{65,67,68};
for(int index = 0; index < bite.length; index++)
System.out.println(new String(bite, index,1));
Upvotes: 2
Reputation: 2944
Edit: Hows about
""+ recBuf[0];//Hacky... not sure if would work
((Byte)recBuf[0]).toString();
Pretty sure that would work.
Upvotes: 0
Reputation: 3587
public static String toString (byte value)
Since: API Level 1 Returns a string containing a concise, human-readable description of the specified byte value.
Parameters value the byte to convert to a string. Returns a printable representation of value.]1 this is how you can convert single byte to string try code as per your requirement
Upvotes: 0
Reputation: 887433
You can make a new byte array with a single byte:
new String(new byte[] { recBuf[0] })
Upvotes: 11