How can i convert a string into a ZZ number?

2019-08-04 01:07发布

I'm using the NTL library to implement ElGamal encryption/decryption algorithm. I've got it to the point that it's working but the algorithm wants the message to be converted to integers so it can be encrypted.
So if i input a number like 1234 everything works ok but how would i go to be able to convert a C++ string (std::string) to a ZZ number and then back from that ZZ number to a string?

LE:

ZZ it's a class that represent a large number.
Ex: 18287348238476283658234881728316274273671623781254124517353

So basically i'm looking to take "Hello World" for example and run it char by char and get the ascii code of the chars so i'll get a number: "72 101 108 108 111 32 87 111 114 108 100"
And then i need to convert this number back to string "Hello World"

Or maybe there's a better way.

标签: c++ ntl elgamal
3条回答
虎瘦雄心在
2楼-- · 2019-08-04 01:38

Here is an easy way to do it:

std::string str("1234567890");
NTL::ZZ number(NTL::INIT_VAL, str.c_str());

Now notice that:

std::cout << str << std::endl; // prints 1234567890
std::cout << number << std::endl; // prints 1234567890
查看更多
叛逆
3楼-- · 2019-08-04 01:40

By far the easiest solution is to realize that you can convert chars to unsigned ints, and unsigned ints to ZZ numbers. Then treat the string as a base-256 number. For instance, "abc" would be 256*"ab" + "c", or 65536 * "a" + 256 * "b" + "c", or ((ZZ(unsigned('a')*256) + ZZ(unsigned('b'))*256) + ZZ(unsigned('c')),

查看更多
唯我独甜
4楼-- · 2019-08-04 01:54

Here is an answer from the NTL author's website:

In addition to the conversions listed, there is a generic conversion from a C-strings (i.e., const char *) to any type T, which is implemented using templates using the input operator >> for type T. So, for example, you can write

    ZZ x = conv<ZZ>("99999999999999999999999");

Source: http://www.shoup.net/ntl/doc/conversions.txt

I tried it, and it worked perfectly.

查看更多
登录 后发表回答