Loop converting to hex - please help


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Loop converting to hex - please help

  1. #1
    Join Date
    Jun 2005
    Posts
    2

    Question Loop converting to hex - please help

    Could someone please explain to me what the following code exactly does?


    for (int i = 0; i < 16; i++) {
    if ((digest & 0xFF) < 0x10) hexValue += "0";
    hexValue += Integer.toHexString(digest & 0xFF);


    I have a program which calculates MD5 hashes from websites to determine whether they have changed since the last visit, and this snippet is part of my source code. I need to know what exactly this code is doing.

    Thanks

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    So, what you wrote wasn't exactly complete, at least I hope that it wasn't.
    Code:
    for (int i = 0; i < 16; i++) {
      if ((digest & 0xFF) < 0x10) hexValue += "0";
      hexValue += Integer.toHexString(digest & 0xFF);
    What this does is print the byte representation of the variable digest 16 times. Essentially it does this:
    Code:
    for (int i = 0; i < 16; i++) {
      hexValue += Integer.toHexString(digest & 0xFF);
    but it prepends a '0' if the result of Integer.toHexString will be only 1 digit.
    For example:
    0x55 => "55"
    0x04 => "04" (instead of just "4", which is what it would be without the if statement)

    I would guess that digest is looping over the first 16 bytes of the file, or 16 random bytes in the file, whichever. Basically on each iteration of the loop it appends the 2 digit hex representation of digest to the end of the hexValue string.

    Hope this helps.
    ~evlich

  3. #3
    Join Date
    Jun 2005
    Posts
    2

    Thanks

    oops, it is supposed to read

    "digest[i] & 0xFF"

    not just "digest & 0xFF"

    my fault i didnt proofread. many thanks for the reply, its a shame i had this code in my program and i didnt really understand what it did

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center