NTL String to ZZ conversion and ZZ to String

2.5k views Asked by At

So I'm working on a basic RSA decryption program and I'm trying to figure out how to convert between a string and a ZZ. I've looked at the following question: How can i convert a string into a ZZ number?, however, I'm a little confused, and the answer there didn't work for me. My code:

fromBase()
{
   string message = "hello world";
   ZZ number (INIT_VAL, message.c_str());
   cerr << number;
}

Gives me the following output.

bad ZZ input
Aborted

So, I thought, no big deal, I'll just try to find what INIT_VAL is supposed to be and that should give me an idea of where to look. But no such luck, I couldn't find anything that looked like it. I trued it with INIT_VAL_STRUCT as well, and got the following error:

base.cpp: In function âNTL::ZZ fromBase(std::string)â:
base.cpp:24: error: âmessageâ is not a type
base.cpp:24: error: expected â,â or â...â before â.â token

Lastly, I tried the solution posted here: Regarding create a NTL class type thinking I could try some type casting. Here's my code:

ZZ fromBase(string message) 
{
   ZZ x;
   x = conv<ZZ>(message);
   return x;
 }

This gave me the following:

g++ base.cpp -lntl
base.cpp: In function âNTL::ZZ fromBase(std::string)â:
base.cpp:19: error: expected primary-expression before â>â token

As if I didn't specify a type.

To conclude, I know that INIT_VAL is a constant, but it doesn't seem to be working with something. I sense I've just got a disconnect, but trying to find it isn't easy. Any help would be appreciated, and any references for the NTL would be greatly appreciated. Sorry for the long post!

(Also, NTL is pretty poorly documented, from what I've seen, do you have any sites that may help a newbie to the library?)

1

There are 1 answers

0
AbcAeffchen On

You want to convert a string, that actually contains non numeric characters into a number.

There is no canonical number of a string, so you cannot do this in one step. C++ can give you the number of a character, which is the ascii number. You can use this function to get the ascii number of a string:

ZZ stringToNumber(string str)
{
    ZZ number = conv<ZZ>(str[0]);
    long len = str.length();
    for(long i = 1; i < len; i++)
    {
        number *= 128;
        number += conv<ZZ>(str[i]);
    }

    return number;
}

You get the string back by this function

string numberToString(ZZ num)
{
    long len = ceil(log(num)/log(128));
    char str[len];
    for(long i = len-1; i >= 0; i--)
    {
        str[i] = conv<int>(num % 128);
        num /= 128;
    }

    return (string) str;
}

If you have some non ascii characters like ö or ß you have to use an other way of converting a character to a number.(But I don't know how exactly this works)