Effective way to get hex string from a byte array using lambdas and streams

拈花ヽ惹草 提交于 2019-12-08 08:42:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!