Hex to Decimal conversion [K&R exercise]

后端 未结 8 1951
梦如初夏
梦如初夏 2021-01-02 23:35

I\'m learning C and I can\'t figure out one of the K&R exercises, the listing:

Exercise 2-3, Write the function htoi(s), which conv

8条回答
  •  一向
    一向 (楼主)
    2021-01-02 23:45

    Processing the string from left to right is simpler and arguably more readable for those comfortable with math. The strategy is realizing that, for example, 1234 = (((1 x 10) + 2) x 10 + 3) x 10 + 4

    In other words, as you process each digit from left to right, multiply the previous total by the base, effectively "moving it left" one position, then add the new digit.

    long decFromHexStr(const char *hexStr)
    {
        int i;
        long decResult = 0;  // Decimal result
    
        for (i=0;  i < strlen(hexStr);  ++i)
        {
            decResult = 16 * decResult + decFromHexChar(hexStr[i]);
        }
        return decResult;
    }
    

    Experienced programmers would probably use a pointer to step through the string instead of treating it as an array:

    long decFromHexStr(const char *pHex)
    {
        long decResult = 0;
    
        while (*pHex != '\0')
        {
            decResult = 16 * decResult + decFromHexChar(*pHex++);
        }
        return decResult;
    }
    

    Since you're learning, it's worth studying the coding style and deciding whether you find it helpful or not, so you'll build good habits early.

    Have fun!

提交回复
热议问题