7

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.

8 Answers 8

11

You can make a new byte array with a single byte:

new String(new byte[] { recBuf[0] })
9

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
0
2

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));
0

What about converting it to char? or simply

  new String(buffer[0])
0
0

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

1
0

Edit: Hows about

""+ recBuf[0];//Hacky... not sure if would work
((Byte)recBuf[0]).toString();

Pretty sure that would work.

0
0

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]));
0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.