[英]How to convert CryptoPP::Integer to char*
我想將myVar從CryptoPP:Integer
轉換為char*
或String:代碼如下:
CryptoPP::Integer myVar = pubKey.ApplyFunction(m);
std::cout << "result: " << std::hex << myVar<< std::endl;
我一直在互聯網上搜索將CryptoPP:Integer
轉換成char*
但我找不到運氣。 因此,要么將CryptoPP:Integer
轉換為char*
,要么我真的不能解決問題,要么我不太了解CryptoPP:Integer
C ++中的CryptoPP:Integer
。
有人能幫助我嗎?
隨着提升:
boost::lexical_cast<std::string>(myVar);
C ++ 98:
std::ostringstream stream;
stream << myVar;
stream.str();
一種方法,不知道更多關於CryptoPP::Integer
除了它明確支持<<
如你的問題所暗示的,是使用std::stringstream
:
std::stringstream ss;
ss << std::hex /*if required*/ << myVar;
使用,例如std::string s = ss.str();
來提取底層的std::string
std::string s = ss.str();
。 然后,只要s
在范圍內,您就可以使用s.c_str()
來訪問const char*
緩沖區。 一旦調用並依賴c_str()
的結果作為執行此操作的行為並且隨后依賴於該結果未定義 ,則不要以任何方式更改s
。
有更簡潔的C ++ 11解決方案,但這需要你(和我)更多地了解類型。
如果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風格字符指針)。
PS
我假設CryptoPP::Integer
對於int
來說不是一個簡單的typedef。
如果要將int
轉換為std::string
,那么您可能只想使用C ++ 11的std::to_string()
。
根據您的需要,有幾種不同的方法可以做到這一點。 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:您的Raw 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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.