NewHelpNeeder
NewHelpNeeder

Reputation: 693

I dont understand something about this piece of code. Hashing

I don't understand few things in following code. Why the length is set to 16? What is the purpose of the ret variable?

Please explain.

I don't understand this:

    foreach (byte a in hash)
    {
        if (a < 16)
            ret += "0" + a.ToString("x");
        else
            ret += a.ToString("x");
    }

Upvotes: 1

Views: 135

Answers (6)

BrokenGlass
BrokenGlass

Reputation: 161002

This code is getting the hashcode in hexadecimal as string with each byte represented as a 2-digit hexadecimal value - you can do it shorter as:

foreach (byte b in hashValue)
   ret +=b.ToString("X2");

or better yet use a StringBuilder instead:

StringBuilder strHash = new StringBuilder();
foreach (byte b in hashValue)
    strHash.Append(b.ToString("X2"));
ret = strHash.ToString();

or a little more elegant (but introducing some overhead) using Linq:

ret = string.Join("",hashValue.Select(b => b.ToString("X2")));

Upvotes: 6

Kevin Gosse
Kevin Gosse

Reputation: 39027

It's just to return the result as an hexadecimal value. If a >= 16, then the hexadecimal value will be two characters long (for instance : A0). IF a < 16, the the hexadecimal value will be one character long (for instance: A), so it's padded with an extra 0 ( => 0A).

Upvotes: 4

Guvante
Guvante

Reputation: 19221

Hexadecimal is base 16, so instead of 0123456789 being the available digits, you have 0123456789ABCDEF. Every byte in a hexedecimal output is represented by 2 digits (16x16 = 256) to avoid ambiguity, so the < 16 check ensures that ToString will output the correct number of characters.

Upvotes: 3

Gabe
Gabe

Reputation: 86818

ret is the value being returned from the function.

Upvotes: 1

Viruzzo
Viruzzo

Reputation: 3025

It's converting the byte value to a 2-characters string representation of its hex value. For values < 16 it would output a single character. It's not a very clean way to do it, hence the confusion.

Upvotes: 1

Jon
Jon

Reputation: 437774

This

if (a < 16) 
    ret += "0" + a.ToString("x"); 
else 
    ret += a.ToString("x"); 

is a worse way of writing

ret += a.ToString("x2");

Its purpose is to produce a string of length exactly 2 which is the hexadecimal form of the number a. Since hex can go up to 15 with just one digit, the code reads "if it would fit in one digit, manually add a zero in front".

Upvotes: 6

Related Questions