optimized itoa function

后端 未结 8 1500
不知归路
不知归路 2021-02-04 06:48

I am thinking on how to implement the conversion of an integer (4byte, unsigned) to string with SSE instructions. The usual routine is to divide the number and store it in a loc

相关标签:
8条回答
  • 2021-02-04 07:12

    @Inge Henriksen

    I believe your code has a bug:

    IntToStr(2701987) == "2701987" //Correct
    IntToStr(27001987) == "2701987" //Incorrect
    

    Here's why your code is wrong:

    modVal = i % numElem10Radix;
    switch (reverseArrayLen[modVal])
    {
        case 5:
            *--p = reverseArray[modVal][4];
        case 4:
            *--p = reverseArray[modVal][3];
        case 3:
            *--p = reverseArray[modVal][2];
        case 2:
            *--p = reverseArray[modVal][1];
        default:
            *--p = reverseArray[modVal][0];
    }
    
    i /= numElem10Radix;
    

    There should be a leading 0 before "1987", which is "01987". But after the first iteration, you get 4 digits instead of 5.

    So,

    IntToStr(27000000) = "2700" //Incorrect

    0 讨论(0)
  • 2021-02-04 07:19

    For unsigned 0 to 9,999,999 with terminating null. (99,999,999 without)

    void itoa(uint64_t u, char *out) // up to 9,999,999 with terminating zero
    {
        *out = 0;
        do { 
            uint64_t n0 = u;
            *((uint64_t *)out) = (*((uint64_t *)out) << 8) | (n0 + '0' - (u /= 10) * 10);
        } while (u);
    }
    
    0 讨论(0)
提交回复
热议问题