十六进制转换成十进制[K&安培; R运动] [英] Hex to Decimal conversion [K&R exercise]
问题描述
我学习C和我想不通的K&放大器之一;ř练习,上市:
I'm learning C and I can't figure out one of the K&R exercises, the listing:
练习2-3,编写函数
htoi(S)
,它转换的字符串
十六进制数字(包括
可选的 0X
或 0X
)转换成等值
整数值。允许的数字
是 0
到 9
, A
到˚F
和 A
通过˚F
。
Exercise 2-3, Write the function
htoi(s)
, which converts a string of hexadecimal digits (including an optional0x
or0X
) into its equivalent integer value. The allowable digits are0
through9
,a
throughf
andA
throughF
.
我想我需要在这里做一些递归,我只是想我不知道了很多关于编号的类型,他们的各种转换方法等。
I suppose I need to do some recursion here, I just guess that I don't know a lot about the numbering types, and their various conversion methodologies, etc.
可能有人给我如何更好地理解一些指点,我不是在找人牵我的手,而是直接向我正确理解的一种手段,所以我可以在最优雅的形式尽可能写,而不是与的printf(%X,技能);
Could someone give me some pointers on how best to understand it, I'm not looking for someone to hold my hand, but instead direct me to a means of proper understanding so I can write this in the most elegant form as possible, and not with printf("%x", skill);
推荐答案
递归是没有必要的。您只需向后循环在字符串(即在单位列开始),单数字的转换时间它的基数位置乘数总结。这是伪code和不处理可选0X preFIX(并且不检查溢出的可能性):
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;
}
我已经离开了易于实现ConvertSingleHexDigittoInt()给你:)
I've left the easy implementation of ConvertSingleHexDigittoInt() to you :)
这篇关于十六进制转换成十进制[K&安培; R运动]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!