What does & 0xff do And MD5 Structure?

后端 未结 2 717
心在旅途
心在旅途 2020-12-14 14:20
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaMD5 {

    public static void main(String[] args) {
        Stri         


        
2条回答
  •  不知归路
    2020-12-14 15:01

    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]));
    

提交回复
热议问题