2

我在处理这段代码时遇到了一些问题。QByteArray::number 应该从哈希中获取 QByteArray 并将其转换为十六进制,但结果比我预期的要短得多。我在想两个输出应该是一样的。我认为这与指针转换有关,但我不明白该转换做得好到足以看到如何进行价值。

谁能解释为什么这两行输出不同的结果?最好在数学方面。

代码

QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData("some string to hash");
qDebug() << QByteArray::number(*(qlonglong*)hash.result().data(), 16);
qDebug() << hash.result().toHex();

输出:

"89bde3ca56c83c47" 
"473cc856cae3bd89e43ff9f62963d6f38372ccbd" 

预期输出:

"473cc856cae3bd89e43ff9f62963d6f38372ccbd" 
"473cc856cae3bd89e43ff9f62963d6f38372ccbd" 

注意:我的实际问题是以 36 为基数,而不是 16,但是有一个方便的 .toHex 方法可以使这更容易显示。

4

2 回答 2

5

在您的 160 位(20 字节)数据处的代码hash.result().data()点。Aqlonglong是您平台上的 64 位(8 字节)数据。

*(qlonglong*)hash.result().data()将哈希结果的前 8 个字节重新解释为数字。您的平台是一个小端平台,因此哈希数据的第一个字节被解释为结果数字的低字节。

因此,64 位数字(以十六进制形式查看)以相反的顺序显示哈希数据的前 8 个字节。您可以在输出中看到:

89 bd ... 3c 47

是初始部分的倒数

47 3c ... bd 89    e4 3f ...
于 2013-02-03T00:07:27.577 回答
-1

You're essentially casting a string (as a const char*) to a long long*, then dereferencing it, and giving whatever numeric value you get back to the constructor of QByteArray. Without using qt classes, you're doing this:

std::string s = "1b3";
const char* cc = s.c_str();

std::cout<<cc<<std::endl;
std::cout<<*(long long*)cc<<std::endl;

Do you get the same string back? No, you do not.

output:
1b3
3367473

It isn't a math thing... it's a problem with casting a char* to a long long* and expecting to have a valid numeric value as a result.

于 2013-02-02T23:54:22.917 回答