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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but whats's that ,16?
16 is the radix - ie base 16, which is hexadecimal. The code basically outputs 1 as "01" instead of "1"
thanks. I also found a simpler way on the forums: sb.append(String.format("%02X", bytes[i]));
@nann yes, using format is the preferred way, but you didn't ask about a better way; you asked "what does this code mean".
you're right. I just wanted to mention this for those who may read this thread later. Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.