Efficient way to get a hexadecimal string from a byte array using lambdas and streams

This is the next question How can I make an IntStream from an array of bytes?

I created a method that converts a given array of bytes into a combined hexadecimal string.

static String bytesToHex(final byte[] bytes) { return IntStream.rang(0, bytes.length * 2) .map(i -> (bytes[i / 2] >> ((i & 0x01) == 0 ? 4 : 0)) & 0x0F) .mapToObj(Integer::toHexString) .collect(joining()); } 

My question is, without using any third-party libraries, is the above code efficient enough? Did I do something wrong or not needed?

+1
source share
1 answer
 static String bytesToHex(final byte[] bytes) { return IntStream.range(0, bytes.length) .mapToObj(i->String.format("%02x", bytes[i]&0xff)) .collect(joining()); } 

although the following may be more effective:

 static String bytesToHex(final byte[] bytes) { return IntStream.range(0, bytes.length) .collect(StringBuilder::new, (sb,i)->new Formatter(sb).format("%02x", bytes[i]&0xff), StringBuilder::append).toString(); } 

Both support parallel processing.

+6
source

Source: https://habr.com/ru/post/978814/


All Articles