Presumably most of the code is clear and the only mystery for you here is this expression:
(bytes[i] & 0xff) + 0x100
The first part:
bytes[i] & 0xff
widens the byte at position i
to an int
value with zeros in bit positions 8-31. In Java, the byte
data type is a signed integer value, so the widening sign-extends the value. Without the & 0xff
, values greater than 0x7f would end up as negative int
values. The rest is then fairly obvious: it adds 0x100, which simply turns on the bit at index 8 (since it is guaranteed to be 0 in (bytes[i] & 0xff)
. It is then converted to a hex String
value by the call to Integer.toString(..., 16)
.
The reason for first adding 0x100 and then stripping off the 1 (done by the substring(1)
call, which takes the substring starting at position 1 through the end) is to guarantee two hex digits in the end result. Otherwise, byte values below 0x10 would end up as one-character strings when converted to hex.
It's debatable whether all that has better performance (it certainly isn't clearer) than:
sb.append(String.format("%02x", bytes[i]));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…