I’m having some trouble with this code. QByteArray::number should take the QByteArray from the hash and convert it to hex, but the result is much shorter than I expected. I was thinking that both outputs should be the same. I’m thinking it has to do with the pointer cast, but I don’t understand what that cast is doing well enough to see how to value is made.
Can anyone explain why these two lines output different results? Preferably in math terms.
Code
QCryptographicHash hash(QCryptographicHash::Sha1);
hash.addData("some string to hash");
qDebug() << QByteArray::number(*(qlonglong*)hash.result().data(), 16);
qDebug() << hash.result().toHex();
Output:
"89bde3ca56c83c47"
"473cc856cae3bd89e43ff9f62963d6f38372ccbd"
Expected Output:
"473cc856cae3bd89e43ff9f62963d6f38372ccbd"
"473cc856cae3bd89e43ff9f62963d6f38372ccbd"
Note: My actual problem is in base 36, not 16, but there was conveniently a .toHex method to make this much easier to show.
In you code
hash.result().data()points at 160bit (20 bytes) of data. Aqlonglongis 64 bits (8 bytes) of data on your platform.*(qlonglong*)hash.result().data()reinterprets the first 8 bytes of the hash result as a number. Your platform is a little endian platform, so the first bytes of the hash data are interpreted as the low bytes of the resulting number.As a result, the 64-bit number (viewed as hex) shows the first 8 bytes of the hash data in reverse order. You can see that in your output:
is the reverse of the initial part of