简体   繁体   English

QByteArray转换为十六进制失败

[英]QByteArray convert to hex fails

I am using GMP in a QT project, and I am trying to use QByteArray to store some of the numbers. 我在QT项目中使用GMP,我正在尝试使用QByteArray来存储一些数字。

When I want to convert a byte array to an mpz_t I am doing the following: 当我想将字节数组转换为mpz_t时,我正在执行以下操作:

const char *hexstring = qbyteval.toHex().toStdString().c_str();
mpz_t myval;
mpz_init (myval);
mpz_set_str(myval, hexstring, 16);

mpz_t zero;
mpz_init(zero);
mpz_set_str(zero, "0", 10);

if(mpz_comp(myval, zero) == 0) {
//...set a breakpoint or do something here. This line shouldn't be reached ever.
}

In my case, qbyteval is never zero. 就我而言, qbyteval永远不会为零。 If I set a breakpoint inside that mpz_comp if block, qbyteval.toHex() is always still a hex string. 如果我在mpz_comp if block中设置断点,则qbyteval.toHex()始终是十六进制字符串。

What is failing, that is causing hexstring to be an empty string (and thus myval =0)? 什么是失败,导致hexstring是一个空字符串(因此myval = 0)?

This looks wrong: 这看起来不对:

const char *hexstring = qbyteval.toHex().toStdString().c_str();

The c_str() function returns a pointer to the internal data in a std::string , and that pointer can become invalidated if you modify or destroy the std::string . c_str()函数返回一个指针,以在内部数据std::string ,如果您修改或破坏该指针将失效std::string In this case, the std::string gets destroyed right after that line runs, because you didn't store it in a variable. 在这种情况下, std::string会在该行运行后立即销毁,因为您没有将它存储在变量中。

There might be more errors like this in your code, but that is the most glaring error. 在您的代码中可能会有更多这样的错误,但这是最明显的错误。 If you still have trouble, I suggest posting a minimal, complete example and better explaining the expected behavior vs the actual behavior, and using a debugger to look at what is happening on every line. 如果您仍有问题,我建议发布一个最小的完整示例,并更好地解释预期行为与实际行为,并使用调试器查看每行发生的情况。

To get a const char* out of the byte array, you must ensure that the buffer isn't a temporary and outlives any and all uses of the pointer: 要从字节数组中获取const char* ,必须确保缓冲区不是临时的,并且比指针的所有使用都要长:

void function(const QByteArray & byteVal) {
  auto const hex = byteVal.toHex();
  mpz_t myval;
  mpz_init (myval);
  mpz_set_str(myval, hex.data(), 16);
  ...
}

This solved for me. 这解决了我。 I didn't initialize myval. 我没有初始化myval。

mpz_t myval;
mpz_set_str(myval.backend().data(), hexstring, 16);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM