【发布时间】:2014-07-19 04:55:41
【问题描述】:
我想要以下 Java 代码的 C++ 版本。
BigInteger x = new BigInteger("00afd72b5835ad22ea5d68279ffac0b6527c1ab0fb31f1e646f728d75cbd3ae65d", 16);
BigInteger y = x.multiply(BigInteger.valueOf(-1));
//prints y = ff5028d4a7ca52dd15a297d860053f49ad83e54f04ce0e19b908d728a342c519a3
System.out.println("y = " + new String(Hex.encode(y.toByteArray())));
这是我对解决方案的尝试。
BIGNUM* x = BN_new();
BN_CTX* ctx = BN_CTX_new();
std::vector<unsigned char> xBytes = hexStringToBytes(“00afd72b5835ad22ea5d68279ffac0b6527c1ab0fb31f1e646f728d75cbd3ae65d");
BN_bin2bn(&xBytes[0], xBytes.size(), x);
BIGNUM* negative1 = BN_new();
std::vector<unsigned char> negative1Bytes = hexStringToBytes("ff");
BN_bin2bn(&negative1Bytes[0], negative1Bytes.size(), negative1);
BIGNUM* y = BN_new();
BN_mul(y, x, negative1, ctx);
char* yHex = BN_bn2hex(y);
std::string yStr(yHex);
//prints y = AF27542CDD7775C7730ABF785AC5F59C299E964A36BFF460B031AE85607DAB76A3
std::cout <<"y = " << yStr << std::endl;
(忽略此案。)我做错了什么?如何让我的 C++ 代码输出正确的值“ff5028d4a7ca52dd15a297d860053f49ad83e54f04ce0e19b908d728a342c519a3”。我也尝试通过执行 BN_set_word(negative1, -1) 来设置negative1,但这也给了我错误的答案。
【问题讨论】:
-
hexStringToBytes(“00中有一个奇怪的引号 ...希望这是一个复制粘贴错误,而不是实际上在您的源文件中 -
你试过
BN_set_negative吗? -
嗯。这似乎也不起作用。只会得到“-AFD72B5835AD22EA5D68279FFAC0B6527C1AB0FB31F1E646F728D75CBD3AE65D”
-
以及 afd 的负面... 是 -afd...
-
也许添加标签“java” - 我通过阅读 BigInteger 的在线文档了解您的要求;可能我误读了在 Java 方面更有经验的人可能能够澄清的文档