Effective way to get hex string from a byte array

2019-05-31 06:20发布

问题:

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.