Naresh Kumar
Naresh Kumar

Reputation: 624

Convert ByteArray To String Java

I am getting byte array value(from server) as below

byte[] byte=9D 37 7B 10 CE 77 8C 49 38 B3 C7 E2 C6 3A 22 9A ;

need to convert it to string as it is

i have tried the following code

String item=new String(byte)

But I'm getting the value as [B@40e5d338

and also i tried using encoding technique

String item=new String(byte,"UTF-8")

�E��V�r��u�i��

Any Help Would be greatly Appreciated .Thank's In Advance

Upvotes: 0

Views: 222

Answers (1)

user2742438
user2742438

Reputation:

The String constructor(s) that take byte[] as parameter create a string by converting the bytes to characters based on an encoding. If you want a string that contains

9D 37 7B 10 CE 77 8C 49 38 B3 C7 E2 C6 3A 22 9A

You'll have to write a method that does that (as far as I know there isn't one in the java library). So basically:

public String toHexString(byte[] arr) {
    if (arr == null || arr.length == 0) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    sb.append(Integer.toHexString(arr[0] & 0xff));
    for (int i = 1; i < arr.length; i++) {
        sb.append(' ').append(Integer.toHexString(arr[i] & 0xff));
    }
    return sb.toString();
}

Upvotes: 2

Related Questions