Search code examples
cnumbershexdecimalnumber-formatting

Convert Hex string of high length to decimal


I'm trying to write a function that can convert a seriesof uint_8 values (set in an array) into one single Decimal number and print it. The values get parsed in an array of known, but not constant length len:

void print_decimal(size_t len, uint8_t buf[len]);

Buf is ordered, so that the most significant digits of the resulting decimal number are at the front of the array, f.e.: -> buf[0] = 1111 1111; buf[1] = 0000 0000 -> Result: 0xFF00 -> Convert to decimal

The issue is, that the length / size of the resulting number exceeds the size of a single cariable like uint64_t (or even 128 Bit types), so simply converting it is not an option.

Are there any smart and easy ways to convert this? F.e. digitwise through an algorithm?


Solution

  • As an example of the repeated division by 0x0A using 'longhand'

          1 2C
        ------
    0A ) 0B BB
         0A
        ---
          1 BB
          1 B8
         -----
             3  l.s. digit
    

    Repeat

          0 1E
        ------
    0A ) 01 2C
         00
        ---
          1 2C
          1 2C
         -----
             0 next l.s. digit
    

    Repeat

          0 03
        ------
    0A ) 00 1E
         00
        ---
          0 1E
          0 1E
         -----
             0 next l.s. digit
    

    Repeat

          0 00
        ------
    0A ) 00 03
         00 
        ---
          0 03
          0 00
         -----
             3 m.s. digit
    

    Result of the string of remainders is 3003 which is decimal of 0xBBB.

    Note that we were never "in base ten". The division was by ten, but the only decimals are the digits that fall out with each repetition.