0

In Javascript I would do it like that:

    const _data = new Uint8Array([0, 1, 2, 4, 5, 6, 7, 8, 9, 77, 100]);
    
    const s = '[' + _data.join(',') + ']';

    console.log(s);

    > [0,1,2,4,5,6,7,8,9,77,100]

Added the solution from SomeDude:

    byte[] b = new byte[]{1,2,3,4,5,77};
    s = Arrays.toString(b);
    System.out.println(s);

    > [1, 2, 3, 4, 5, 77]

2 Answers 2

1

The simplest method:

byte[] b = new byte[]{1,2,3,4,5};
String s = Arrays.toString(b);

Or

 StringBuilder sb = new StringBuilder("[");
 for ( int i = 0; i < b.length; i++ ) sb.append(String.valueOf(b[i]) + ",");
 sb.append("]");
 String s = sb.toString();

Or with streams if you have an array of boxed bytes like:

Byte[] B = new Byte[]{1,2,3,4,5};
String s = "[" + Stream.of(B).map(Object::toString).collect(Collectors.joining(",")) + "]";
System.out.println(s);
Sign up to request clarification or add additional context in comments.

3 Comments

yep. I was wondering if there is a possibility to do it without the conversion in a loop; the code is a bit chunky compared to JS - 4 lines of code vs. one. And the need of an extra array. But this seem to be unavoidable.
Ahh! Arrays.toString. This is it. the 'json style' brackets are already included, so the final code is like this: byte[] b = new byte[]{1,2,3,4,5,77}; s = Arrays.toString(b); System.out.println(s);
@Gisela yes right forgot that..no need to add "[,]"
0

This may not be the best way, but this is a way:

final var data = new byte[] { 0, 1, 2, 4, 5, 6, 7, 8, 9, 77, 100 };

final var s = "[" + 
    IntStream.range(0, data.length)
        .mapToObj(i -> Byte.toString(data[i]))
        .collect(Collectors.joining(",")) +
    "]";

System.out.println(s);

3 Comments

unfortunately not. - Arrays.stream cannot handle byte arrays
@Gisela: right - didn't notice that they array was byte data :(
Updated my answer to work with byte array

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.