Search code examples
bit-manipulationbignumpic

Convert Decimal to Hex when no datatype can hold the full number


This is an almost exact duplicate of my own question a few weeks ago.

Convert Hex to Decimal when no datatype can hold the full number

This time, it is the reverse. I have the number (in a handy null terminated string) and I need the bytes that make this number. However, I am working in a 32 bits architecture for a micro controller, therefore I don't have the possibility of using the atoi, as the number is larger than 32 bits.

Does anyone have an idea on how to reverse the algorithm provided in the first link, as to get back the original result? My modulo arithmetic skills are failing me.

Quick Example: 155.207.231.135 to 0x[24][23][12][66][9F] (the brackets separate the bytes)


Solution

  • You can do something similar to BigInt division.

    a = atoi of lower 7 decimal digits
    b = atoi of remaining upper decimal digits
    
    
    for (int i = 0; i < 5; i++)
    {
        a += 10000000 * (b % 256);
        b /= 256;
        Result[i] = a % 256;
        a /= 256;
    }