Why is my MD5 value printing with extra "f" characters?
I have strange problem when using at() method of std::string. I'd like to calculate md5 hash for given string using this library: http://sourceforge.net/projects/libmd5-rfc/files/ Hash is calculated correctly, but there is a problem with printing it human way. The output is:
af04084897ebbf299b04082d105ab724
ffffffaf040848ffffff97ffffffebffffffbf29ffffff9b04082d105affffffb724
Code is:
#include <stdio.h>
#include<string>
#include<iostream>
extern "C" {
#include "md5.h"
}
int main()
{
md5_state_t state;
md5_byte_t digest[16];
std::string callid("f83bc385-26da-df11-95d5-0800275903dd@pc-archdev");
md5_init(&state);
md5_append(&state, (const md5_byte_t*)callid.c_str(), callid.length());
std::string callid_digest((const char*)digest, 16);
for(int i = 0; i < 16; ++i) {
printf("%02x", digest[i]);
}
printf("\n");
for(int i = 0; i < 16; ++i) {
const char c = callid_digest.开发者_Go百科at(i);
printf("%02x", c);
}
printf("\n");
}
Where do the "f" characters come from ?
Your byte values are being sign-extended.
That happens when you promote the (signed) char to a wider type and the top bit is set, because it tries to preserve the sign (which is why you're seeing the extra f
characters only for values greater than 0x7f
). Using an unsigned char
should fix the problem:
const unsigned char c = callid_digest.at(i); // may need to cast.
精彩评论