将编码的 std::string 从 Base16 转换为 Base10?
以下内容应该适合您。下面的代码向您展示了如何使用 C 风格的字符串来实现这一点,这很容易概念化。您在Convert CryptoPP::Integer to LPCTSTR 的上一个问题有参考。
#include <iostream>
#include <string>
using namespace std;
#include "cryptlib.h"
#include "integer.h"
using namespace CryptoPP;
int main(int argc, char* argv[])
{
string s2, s1 =
"bbb91c1c95b656f386b19ab284b9c0f66598e7761cd71569734bb72b6a7153b77613a6cef8e63"
"e9bd9bb1e0e53a0fd8fa2162b160fcb7b461689afddf098bfc32300cf6808960127f1d9f0e287"
"f948257f7e0574b56585dd1efe1192d784b9c93f9c2215bd4867062ea30f034265374fa013ab4"
"5af06cd8554fd55f1c442c2ed";
// Append 'h' to indicate Base16
// Integer n((s1 + "h").c_str());
// Prepend '0x' to indicate Base16
Integer n(("0x" + s1).c_str());
// Convert to Base10
s2 = IntToString<Integer>(n, 10);
cout << s2 << endl;
return 0;
}
上面的代码向您展示了如何使用 C 风格的字符串来实现,这很容易概念化。另一种方法是使用 Crypto++ Pipeline 将 ASCII 字符串转换为大端字节数组。
#include <iostream>
#include <string>
using namespace std;
#include "cryptlib.h"
#include "integer.h"
#include "filters.h"
#include "hex.h"
using namespace CryptoPP;
int main(int argc, char* argv[])
{
string s3, s2, s1 =
"bbb91c1c95b656f386b19ab284b9c0f66598e7761cd71569734bb72b6a7153b77613a6cef8e63"
"e9bd9bb1e0e53a0fd8fa2162b160fcb7b461689afddf098bfc32300cf6808960127f1d9f0e287"
"f948257f7e0574b56585dd1efe1192d784b9c93f9c2215bd4867062ea30f034265374fa013ab4"
"5af06cd8554fd55f1c442c2ed";
// Use a HexDecoder to convert to big-endian array
StringSource ss(s1, true, new HexDecoder(new StringSink(s2)));
// Use big-endian array to construct n
Integer n((const byte*)s2.data(), s2.size());
// Convert to Base10
s3 = IntToString<Integer>(n, 10);
cout << s3 << endl;
return 0;
}
这是使用 Crypto++ Pipeline 执行转换的另一种方法。
#include <iostream>
#include <string>
using namespace std;
#include "cryptlib.h"
#include "integer.h"
#include "filters.h"
#include "hex.h"
using namespace CryptoPP;
int main(int argc, char* argv[])
{
string s2, s1 =
"bbb91c1c95b656f386b19ab284b9c0f66598e7761cd71569734bb72b6a7153b77613a6cef8e63"
"e9bd9bb1e0e53a0fd8fa2162b160fcb7b461689afddf098bfc32300cf6808960127f1d9f0e287"
"f948257f7e0574b56585dd1efe1192d784b9c93f9c2215bd4867062ea30f034265374fa013ab4"
"5af06cd8554fd55f1c442c2ed";
// Use a source to convert to big-endian array
StringSource ss(s1, true, new HexDecoder);
// Use big-endian array to construct n
Integer n;
n.Decode(ss, ss.MaxRetrievable());
// Convert to Base10
s2 = IntToString<Integer>(n, 10);
cout << s2 << endl;
return 0;
}
如果您对将 ASCII 字符串转换为字节数组以进行内部表示的算法感兴趣,请参阅StringToInteger in integer.cpp。它反复除以基数(2、8、10、16 等)。