如何将 CryptoPP::Integer 转换为 char*
How to convert CryptoPP::Integer to char*
我想将myVar从CryptoPP:Integer
转换为char*
或字符串:代码如下:
CryptoPP::Integer myVar = pubKey.ApplyFunction(m);
std::cout << "result: " << std::hex << myVar<< std::endl;
我一直在互联网上搜索将CryptoPP:Integer
转换为char*
但我没有运气找到。所以,要么CryptoPP:Integer
转换为char*
真的是所有的问题,要么我不太了解C++中的类型 CryptoPP:Integer
.
有人可以帮我吗?
一种方法是使用std::stringstream
,除了它明确支持您的问题所暗示的<<
之外,对CryptoPP::Integer
了解更多
std::stringstream ss;
ss << std::hex /*if required*/ << myVar;
使用std::string s = ss.str();
提取底层std::string
。然后,可以使用 s.c_str()
访问const char*
缓冲区,只要s
在范围内。一旦你调用并依赖c_str()
的结果,就不要以任何方式改变s
,因为这样做的行为以及随后依赖该结果的行为是不确定的。
有更整洁的C++11解决方案,但这需要您(和我(了解有关该类型的更多信息。
带 Boost:
boost::lexical_cast<std::string>(myVar);
C++98:
std::ostringstream stream;
stream << myVar;
stream.str();
几种不同的方法可以做到这一点,具体取决于您想要什么。 在这种情况下,char*
没有提供足够的信息。
以下是使用插入运算符时获得的内容:
byte buff[] = { 'H', 'e', 'l', 'l', 'o' };
CryptoPP::Integer n(buff, sizeof(buff));
cout << "Oct: " << std::oct << n << endl;
cout << "Dec: " << std::dec << n << endl;
cout << "Hex: " << std::hex << n << endl;
这导致:
$ ./cryptopp-test.exe
Oct: 4414533066157o
Dec: 310939249775.
Hex: 48656c6c6fh
但是,如果您想获取原始字符串"hello"(re:您的原始 RSA 项目(:
byte buff[] = { 'H', 'e', 'l', 'l', 'o' };
CryptoPP::Integer n(buff, sizeof(buff));
size_t len = n.MinEncodedSize();
string str;
str.resize(len);
n.Encode((byte *)str.data(), str.size(), Integer::UNSIGNED);
cout << "Str: " << str << endl;
这导致:
$ ./cryptopp-test.exe
Str: Hello
但是,如果您只想在 Integer
中使用字符串,则:
Integer i("11111111111111111111");
ostringstream oss;
oss << i;
string str = oss.str();
cout << str << endl;
这导致:
$ ./cryptopp-test.exe
1111111111111111111.
如果CryptoPP::Integer
可以发送到像std::cout
这样的输出流(正如您的代码所建议的那样(,那么您可以使用std::ostringstream
:
#include <sstream> // For std::ostringstream
....
std::string ToString(const CryptoPP::Integer& n)
{
// Send the CryptoPP::Integer to the output stream string
std::ostringstream os;
os << n;
// or, if required:
// os << std::hex << n;
// Convert the stream to std::string
return os.str();
}
然后,一旦您有了std::string
实例,您就可以使用 std::string::c_str()
将其转换为 const char*
。
(但我认为在C++代码中,您应该使用像 std::string
这样的安全字符串类,而不是原始的 C 样式字符指针(。
附言我假设CryptoPP::Integer
对于int
来说不是一个微不足道的 typedef.
如果要将int
转换为std::string
,那么您可能只想使用C++11的std::to_string()
。
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将函数参数"const char*"转换为"std::string_view"是
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 如何在虚幻引擎4中将char*转换为TCHAR?
- C++:将模板类型 char 转换为 std::string
- strcmp/char* 转换无法按预期工作
- C++中的SQLite char*转换
- 无法从 const char* 转换为 const char *&
- 在 C++ 中将 char 转换为 int,而无需符号位传播
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 试图使用strCMP时的char转换错误
- 无法从'const char *'转换为'LPCTSTR'
- 将 std::vector<char> 转换为字符* 会导致字符缺陷
- 使用 static_cast 将 char 转换为 int c++
- 如何在 C++(MFC) 中将 char* 转换为 LPCTSTR
- 无法将const char转换为字符串构造字符串