Hex to Decimal conversion [K&R exercise]

后端 未结 8 1943
梦如初夏
梦如初夏 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:53

    Recursion is not necessary. You simply need to loop backwards over the string (i.e. starting in the units column), summing the single digit conversion times it's radix position multiplier. This is pseudocode and does not handle the optional 0x prefix (and is not checking for possibility of overflow):

    long total = 0;
    long multiplier = 1;
    for (int i = string.length - 1; i >= 0 i--)
    {
       digit = ConvertSingleHexDigittoInt(string[i]);
       total += digit * multiplier;
       multiplier *= 16;
    }
    

    I've left the easy implementation of ConvertSingleHexDigittoInt() to you :)

提交回复
热议问题