Lawrence wrote:
> Hex rappresent at most 16 different combinations per digit, so two hex
> digit rappresent 256 combination
Hex represents a value with the base of 16. One "digit" can
therefore represent numbers from 0 to 15. How many "combinations"
can be represented depends on the bitlength. Integer (used here)
can hold 32 Bits, so a Hex-number can be up to 8 Hex-digits
(aka Nibbles) long.
> , 8 bits, 1 byte.
> Then it does some kind of implicit conversion applying and bit wise
> operation between
> 0xFF which is like a bit string of 8 1s.
The usage of the mask has the reason to covert the signed byte
to an unsigned int-value. Alternatively you can do a
digest[i] + (digest[i] < 0 ? 256 : 0);
But this is much more complicated to read and understand what
is intended to happen here.
If you don't do this kind of thing and you just do a
Integer.toHexString((int) digest[i]);
a set value of e.g. 255 will lead to the hex-value
of FFFFFFFF to be returned. Why? If you set 255 (0xff)
to a byte that is signed, the value will be -1 after
that (that's what 0xff represents). If you just cast
it to an int, the value still is -1, there are just
more bits being set (0xffffffff).
The construct (digest[i] & 0xff) tells the VM, to
cast digest[i] to int (0xffffffff) and do a logical
AND with the value 0xff). The result is 0x000000ff,
which is the same value as being set previously.
> The result should be an number (what, hex or int or even a byte)
> that if is smaller than 16 means it will be of only one digit,
> therefore
> a 0 is added in front of the hex digit.
That's the first check. Alternatively the if-statement
can be if(digest[i] >= 0 && digest[i] < 16) but again
this is harder to read and understand two weeks later.
In C you just would use "unsigned byte" (I know byte
doesn't exist in C but I don't want to start confusing
things staring to use char here). In Java you always
have to do these kind of things when handling unsigned
data with signed types.
Regards, Lothar
--
Lothar Kimmeringer E-Mail:
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)
Always remember: The answer is forty-two, there can only be wrong
questions!