Http.hash.md5 example formatting code improvements

Hi All,

I’ve been having some strange results from my agent when it creates an md5 hash, It wasn’t until my flatmate recognised what looked like a C printf format function that we realised what was wrong.
… Well not wrong exactly, but not what the average user might be expecting.

Here is the code in question:

function BlobToHexString(data) { local str = "0x"; foreach (b in data) str += format("%00X", b); return str; }

From this http.hash.md5 documentation page: https://electricimp.com/docs/api/http/hash/md5/

Now, the average user thinks of this when an md5 hash comes to mind. (at least it does with me, please forgive me if this is not the norm!)

433a386c7c6ee8e3ed7292d12e0b6f24

Now if I remove the ‘0x’ from the beginning of every byte, and switch the ‘%00X’ to %00x’ (For lowercase), the code then looks like this:
function BlobToHexString(data) { local str = ""; foreach (b in data) str += format("%00x", b); return str; }

But if I run it on a hash, I get this:
433a386c7c6ee8e3ed7292d12eb6f24

It’s subtle, so I’ll show how it should look:
433a386c7c6ee8e3ed7292d12e0b6f24

The Zero(s) are missing!

The solution to this, as far as I can see is to use a slightly different formatting function:
foreach (b in data) str += format("%02x", b);

Notice the %02x instead of %00X

Thanks to this stackoverflow question for providing me with the solution:
http://stackoverflow.com/questions/12062916/printing-leading-zeroes-for-hexadecimal-in-c

Use "%02x".

The two means you always want the output to be two characters wide.

The zero means if padding is necessary, to use zeros instead of spaces.

Hopefully, this is of use to someone, and maybe the IDE documentation could do with a bit more detail for more novice users?

Thanks - J

That looks like a bug in our example code - thanks for the catch @jpwsutton!

We’ll get that updated right away :slight_smile: