Qadir Hussain
Qadir Hussain

Reputation: 8856

how to store a byte [] into a single variable in android/java

I have a String str = "admin:admin"

i want to convert it in the ASCII.

I have tried str.getByte("US-ASCII"); this is returning me a byte[] array (i.e [97, 100, 109, 105, 110, 58, 97, 100, 109, 105, 110]). i want the ASCII value in a single String variable. how can I do this.

simple i want this String strASCII = "971001091051105897100109105110"

is this possible?

I also tried this

StringBuilder builder = new StringBuilder();
    for (int i=0; i<=b.length; i++) {
        builder.append(b);
    }
    String result = builder.toString();

but now its returning me something like this

[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0[B@405666e0

what is this?

Upvotes: 1

Views: 931

Answers (2)

Qadir Hussain
Qadir Hussain

Reputation: 8856

using simple for Loop and String builder we can do this also.

 StringBuilder builder = new StringBuilder();
    for (int i = 0; i < b.length; i++) {
        builder.append(b[i]);
    }
    String result = builder.toString();

Upvotes: 0

Alexis King
Alexis King

Reputation: 43842

Try simply looping with StringBuilder:

StringBuilder builder = new StringBuilder();
for (byte b : arr) {
    builder.append(b);
}
String result = builder.toString();

You could, of course, do the same thing with string concatenation, but using StringBuilder explicitly will be faster for lots of small appends.

Upvotes: 1

Related Questions