Decoding Hex: What does this line do (len & 0x01) != 0

后端 未结 3 1640
北海茫月
北海茫月 2021-01-25 21:33

I was going through a piece of code in the Apache commons library and was wondering what these conditions do exactly.

public static byte[] decodeHex(final char[         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-25 21:59

    It's a 1337 (high performance) way of coding:

    if (len % 2 == 1)
    

    i.e. is len odd. It works because the binary representation of every odd integer has its least significant (ie last) bit set. Performaning a bitwise AND with 1 masks all other bits, leaving a result of either 1 if it's odd or 0 if even.

    It's a carryover from C, where you can code simply:

    if (len & 1)
    

提交回复
热议问题