问题
This is a follow-up question of How can I make an IntStream from a byte array?
I created a method converting given byte array to a joined hex 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 that, not using any 3rd party libraries, is above code effective enough? Did I do anything wrong or unnecessary?
回答1:
static String bytesToHex(final byte[] bytes) {
return IntStream.range(0, bytes.length)
.mapToObj(i->String.format("%02x", bytes[i]&0xff))
.collect(joining());
}
though the following might be more efficient:
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.
来源:https://stackoverflow.com/questions/27181383/effective-way-to-get-hex-string-from-a-byte-array-using-lambdas-and-streams