Hex to Decimal conversion [K&R exercise]

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

    Mitch has the basic idea right, but let's take it in a little more detail.

    A hex number is just base 16, which means the digits (from right to left) have the values as

    digit × 160 (ie, 1)
    digit × 161 (ie, 16)
    digit × 162 (256)

    and so on. So, 0xE is 14, for example.

    What you'll want is a loop starting at the right end of the string. Let's say the string is s, length(s) is the length of the string. In pseudocode, you want

    value = 0
    r = 1   // ask yourself "what values does r take as this proceeds?"
    for i from length(s)-1 to 0   // Ask yourself "why length(s)-1?"
       value = value + (digitval(s[i])*r)
       // get ready for the next digit
       r = r * 16
    

    digitval(char c) needs to be a function that translates a checract in "0123456789ABCDEF" into the values between 0 and 15 (inclusive.) I'll leave that as an exercise, with one hint: "arrays".

    be careful with one extra issue; since you could have a leading "0" or "0x" you need to make sure you handle those cases.

提交回复
热议问题