Home > database >  Converting HEXA 64 bits numbers to int
Converting HEXA 64 bits numbers to int

Time:09-26

I'm making a college job, a conversion between hexa numbers enclosed in a stringstream. I have a big hexa number (a private key), and I need to convert to int, to put in a map<int,int>. So when I run the code, the result of conversion is the same for all the two hexa values inserted, what is incorrect, it should be differente results after conversion. I think it's an int sizes stack problem, because when I insert short hexas, it works greatly. As shown below the hexa has 64 bits.

Any idea to get it working?

int main() 
{
    unsigned int x;   
    std::stringstream ss;
    ss << std::hex << "0x3B29786B4F7E78255E9F965456A6D989A4EC37BC4477A934C52F39ECFD574444";
    ss >> x;

    std::cout << "Saida" << x << std::endl;
    // output it as a signed type
    std::cout << "Result 1: " << static_cast<std::int64_t>(x) << std::endl;

    ss << std::hex << "0x3C29786A4F7E78255E9A965456A6D989A4EC37BC4477A934C52F39ECFD573344";
    ss >> x;
    std::cout << "Saida 2 " << x << std::endl;
    // output it as a signed type
    std::cout << "Result 2: " << static_cast<std::int64_t>(x) << std::endl;
}

CodePudding user response:

Each hexadecimal digit equates to 4 bits (0xf -> 1111b). Those hex strings are both 64 x 4 = 256 bits long. You're looking at a range error.

CodePudding user response:

  1. Firstly, the HEX numbers in your examples do not fit into an unsigned int.
  2. You should clear the stream before loading the second HEX number there.
...
std::cout << "Result 1: " << static_cast<std::int64_t>(x) << std::endl;

ss.clear();
ss << std::hex << "0x3C29786A4F7E78255E9A965456A6D989A4EC37BC4477A934C52F39ECFD573344";
ss >> x;
...

CodePudding user response:

You need to process the input 16 characters at a time. Each character is 4 bits. The 16 first characters will give you an unsigned 64-bit value. (16x4 is 64)

Then you can put the fist value in a vector or other container and move on to the next 16 characters. If you have questions about string manipulation, search this site for similar questions.

  • Related