3

I got a code for MD5 hash generation in Java. It generates the hash in byte array "bytes" and then converts to integer and then to string as follows:

byte[] bytes=md.digest(textToHash.getBytes());

StringBuilder sb=new StringBuilder();
for(int i=0;i<bytes.length;i++)
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));

I understood that bytes[i] & 0xff converts byte to integer of 32 bit length copying the byte to the least significant byte of the integer:

What does value & 0xff do in Java?

However I couldn't understand what + 0x100, 16 does in the parentheses at line 4 of the above code. Your help is appreciated.

Community
  • 1
  • 1
narin.sri
  • 31
  • 1
  • 3

1 Answers1

3

Breaking down Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1):

  • Adding 0x100 (which is 256 decimal) sets the 9th bit to 1, which guarantees the binary number representation of the result has exactly 9-bits. You could equivalently do & 0x100.
  • After setting bit 8, the result from the toString() will be 9 chars long (of zeroes and ones).
  • substring(1) effectively ignores bit 8 and outputs the lower 8 bits

So what?

This code puts leading zeroes on values, so all values are exactly 8 binary characters. There's no way to make Integer.toString() alone do this.

Bohemian
  • 412,405
  • 93
  • 575
  • 722