How to convert CryptoPP::Integer to char*

佐手、 提交于 2019-12-01 21:15:48

One way, without knowing much more about CryptoPP::Integer other than it clearly supports << as implied by your question, is to use std::stringstream:

std::stringstream ss;
ss << std::hex /*if required*/ << myVar;

Extract the underlying std::string using, say std::string s = ss.str();. You can then use s.c_str() to access the const char* buffer for as long as s is in scope. Don't change s in any way once you've called and relied upon the result of c_str() as the behaviour of doing so and subsequently relying on that result is undefined.

There are neater C++11 solutions but that requires you (and me) to know more about the type.

With Boost:

boost::lexical_cast<std::string>(myVar);

C++98:

std::ostringstream stream;
stream << myVar;
stream.str();

If CryptoPP::Integer can be sent to output streams like std::cout (as your code seems to suggest), then you can use 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();
}

Then, once you have a std::string instance, you can convert it to const char* using std::string::c_str().
(But I think in C++ code you should use a safe string class like std::string in general, instead of raw C-style character pointers).


PS
I'm assuming CryptoPP::Integer is not a trivial typedef for an int.
If you want to convert an int to a std::string, then you may want to just use C++11's std::to_string().

There's a few different ways you can do this, depending on what you want. char* does not provide enough information in this case.

Here's what you get when using the insertion operator:

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;

That results in:

$ ./cryptopp-test.exe
Oct: 4414533066157o
Dec: 310939249775.
Hex: 48656c6c6fh

However, if you want to get the original string "hello" (re: your Raw RSA project):

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;

That results in:

$ ./cryptopp-test.exe
Str: Hello

If, however, you just want the string used in an Integer, then:

Integer i("11111111111111111111");    
ostringstream oss;

oss << i;    
string str = oss.str();

cout << str << endl;

That results in:

$ ./cryptopp-test.exe
1111111111111111111.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!