Solidity – Detailed Explanation of the Output of keccak256() Function

hashhash-algorithmkeccaksolidity

I've been looking through articles and youtube videos and I still don't get it.

I'm trying to get to a place where I can explain it to myself in simple terms (I'm still pretty new to coding).

What I have so far is:

"keccak256() maps the input into a random 256-bit hexadecimal number."

I don't yet understand what the output exactly is.

Using a keccak256 hash generator, I know it's supposed to look something like this:

97fc46276c172633607a331542609db1e3da793fca183d594ed5a61803a10792

hexadecimal -> numbers that uses the base-16 system (This part I understand, and I can see it in the address.)

256-bit -> 256 binary digits (This part I don't. I'm not seeing how it relates to the output.)

Thank you in advance.

Best Answer

To preface, let's talk about hex.

Hexadecimal is just a representation of a value. So the hexadecimal representation of the binary number 1100 is C. You can verify this by first converting 1100 in binary to decimal (it's 1 * 8 + 1 * 4 = 12) and then converting that into hexadecimal which gives us C.

So 1100 in binary is C in hexadecimal which is also 12 in decimal (and it's 14 in octal, and whatever else you want in whatever base you choose!)


With that out of the way, let's think about what exactly "256-bit hexadecimal number" means.

Well we already know what a "hexadecimal number is", it's a representation of a number using base-16 (the hex base). So that means we should expect the output to be formatted a hexadecimal number. But we haven't talked at all about what that hexadecimal number is!

256-bit is talking about the size of the number that will be returned. I could have just as easily said 32-byte or 64-nibble hexadecimal number. So being a 256-bit number, it can only hold values between 0 and 2^256 - 1 (if we are assuming the number is not signed).

If you look at your hex output 97fc46276c172633607a331542609db1e3da793fca183d594ed5a61803a10792 and count the number of characters there are there, you'll count 64. Each hex character represents 4 bits, so we have 256 bits represented here!