2010-10-20 80 views
3

在std :: string的()方法中使用时出现奇怪的问题。我想使用这个库来计算给定字符串的md5散列值:http://sourceforge.net/projects/libmd5-rfc/files/ 散列值的计算是正确的,但是打印它的方式存在问题。输出是:为什么我的MD5值用额外的“f”字符打印?

af04084897ebbf299b04082d105ab724 
ffffffaf040848ffffff97ffffffebffffffbf29ffffff9b04082d105affffffb724 

代码是:

#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("[email protected]"); 

     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.at(i); 
      printf("%02x", c); 
     } 

     printf("\n"); 
    } 

在哪里的 “F” 字从何而来?

+0

pejotr,我超买的代码,因为它被认为是更好的问题是自我包含的越好。我也改变了标题,使其更能表明问题。希望你不介意。干杯。 – paxdiablo 2010-10-20 18:12:03

回答

8

您的字节值正在被符号扩展。

也就是说,当你推动(签字)字符更广泛的类型和最高位恰好设置,因为它试图保护标志(这就是为什么你看到的额外f字符只为大于0x7f值)。使用unsigned char应该解决的问题:

const unsigned char c = callid_digest.at(i); // may need to cast. 
+1

或者更好,使用'unsigned char'的'md5_byte_t'。 – Potatoswatter 2010-10-20 18:04:18

+1

或使用std :: cout,以便自动检测类型。 – 2010-10-20 18:19:29

相关问题