JuiCe
JuiCe

Reputation: 4201

Convert a single byte to a string?

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

Answers (8)

Taras Tsugrii
Taras Tsugrii

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

amicngh
amicngh

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

waqaslam
waqaslam

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

Sujay
Sujay

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

meiamsome
meiamsome

Reputation: 2944

Edit: Hows about

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

Pretty sure that would work.

Upvotes: 0

Sourabh Saldi
Sourabh Saldi

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

Shark
Shark

Reputation: 6610

What about converting it to char? or simply

  new String(buffer[0])

Upvotes: 0

SLaks
SLaks

Reputation: 887433

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

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

Upvotes: 11

Related Questions