为什么我的 MD5 值打印时带有额外的“f”?人物?
使用 std::string 的 at() 方法时遇到奇怪的问题。我想使用此库计算给定字符串的 md5 哈希值: http://sourceforge.net /项目/libmd5-rfc/文件/ 哈希计算正确,但以人为方式打印存在问题。输出是:
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("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.at(i);
printf("%02x", c);
}
printf("\n");
}
“f”字符从哪里来?
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.at(i);
printf("%02x", c);
}
printf("\n");
}
Where do the "f" characters come from ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的字节值正在进行符号扩展。
当您将(有符号)字符提升为更宽的类型并且设置了最高位时,就会发生这种情况,因为它试图保留符号(这就是为什么您只看到值的额外
f
字符大于0x7f
)。使用unsigned char
应该可以解决这个问题: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 than0x7f
). Using anunsigned char
should fix the problem: