Академический Документы
Профессиональный Документы
Культура Документы
widens the byte at position i to an int value with zeros in bit positions 831. 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 hexStringvalue by the call
toInteger.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]));
(OR)
It's a really messy way of translating to a hexadecimal string.
(OR)
Bytes are signed: they could be negative. When a negative byte is
handled by Integer.toString() generates a string beginning with "FFFFFF",
but this doesn't happen with positive bytes, so the length of the resulting
string is not fixed. The & 0xff converts the byte to an unsigned integer.
Then 0x100 is added to ensure that the hex string is 3 chars long; this is
needed because we want a string with 2 hex digits for each byte but a
byte between 0 and 15 would produce 1 char only. Finally the third digit is
discarded with substring(1).