解码hex:这行是做什么的(len&0x01)!= 0
我正在浏览Apache commons库中的一段代码,并想知道这些条件究竟是做什么的。
public static byte[] decodeHex(final char[] data) throws DecoderException { final int len = data.length; if ((len & 0x01) != 0) { // what does this condition do throw new DecoderException("Odd number of characters."); } final byte[] out = new byte[len >> 1]; // two characters form the hex value. for (int i = 0, j = 0; j < len; i++) { int f = toDigit(data[j], j) << 4; j++; f = f | toDigit(data[j], j); j++; out[i] = (byte) (f & 0xFF); // what is happening here. } return out; }
提前致谢。
这是一种1337 (高性能)编码方式:
if (len % 2 == 1)
即是len
奇数。 它的工作原理是因为每个奇数的二进制表示都设置了最低有效位(即最后一位)。 使用1
掩码对所有其他位执行按位AND
,如果为奇数则为1
如果为偶数则为0
。
它是来自C的遗留物,您可以在其中进行简单编码:
if (len & 1)
这将检查len
的二进制写入中的最后一位是否为1
。
xxxxxxxy & 00000001
如果y
为1
则给出1
如果y
为0
则给出0
,忽略其他数字。
如果y
为1
,则char数组的长度为奇数,这不应该在此hex写入中发生,因此exception。
另一种解决方案是
if (len%2 != 0) {
在我看来哪个更清楚。 我怀疑在循环真正重要之前的轻微性能提升。
该行检查len是否为奇数。 如果len不是奇数,则len&1将等于0.(1和0x01是相同的值,0x01只是hex表示法)