将非十进制数转换为另一个非十进制数
并不是说这需要大量工作,但我知道将非十进制转换为另一个非十进制的唯一方法是首先将数字转换为十进制,然后采取第二步将其转换为新的基数。例如,要将 456(基数为 7)转换为 567(基数为 8),我会计算 456 的十进制值,然后将该值转换为基数 8...
是否有更好的方法直接从 7 转换为 8 ?或与此相关的任何基地到任何其他基地?
这是我所拥有的:
//source_lang and target_lang are just the numeric symbols, they would be "0123456789" if they were decimal, and "0123456789abcdef" if hex.
private string translate(string num, string source_lang, string target_lang)
{
int b10 = 0;
string rv = "";
for (int i=num.Length-1; i>=0; i--){
b10 += source_lang.IndexOf( num[i] ) * ((int)Math.Pow(source_lang.Length, num.Length -1 - i));
}
while (b10 > 0) {
rv = target_lang[b10 % target_lang.Length] + rv;
b10 /= target_lang.Length;
}
return rv;
}
Not that it's a lot of work, but the only way I know to convert a non-decimal to another non-decimal is by converting the number to decimal first, then take a second step to convert it to a new base. For example, to convert 456 (in base 7) to 567 (in base 8), I would calculate the decimal value of 456, then convert that value into base 8...
Is there a better way to go directly from 7 to 8? or any base to any other base for that matter?
Here's what I have:
//source_lang and target_lang are just the numeric symbols, they would be "0123456789" if they were decimal, and "0123456789abcdef" if hex.
private string translate(string num, string source_lang, string target_lang)
{
int b10 = 0;
string rv = "";
for (int i=num.Length-1; i>=0; i--){
b10 += source_lang.IndexOf( num[i] ) * ((int)Math.Pow(source_lang.Length, num.Length -1 - i));
}
while (b10 > 0) {
rv = target_lang[b10 % target_lang.Length] + rv;
b10 /= target_lang.Length;
}
return rv;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您并没有真正转换为基数 10。您是将其转换为数字数据类型而不是字符串表示形式。如果有的话,您可以将其转换为二进制:)有必要区分“整数”(本质上没有基数)和“整数的文本表示”(有基数)。
在我看来,这似乎是一个明智的选择。然而,您的转换例程肯定不是特别有效。我会将您的代码分成
Parse
和Format
方法,然后Convert
方法可以类似于:(您可以使用
当然,如果您确实需要这种灵活性,我会尝试创建一个新类来表示“数字表示”。其中包含
Parse
、Format
和Convert
。)You're not really converting into base 10. You're converting it into a numeric data type instead of a string representation. If anything, you're converting it into binary :) It's worth distinguishing between "an integer" (which doesn't intrinsically have a base) and "the textual representation of an integer" (which does).
That seems like a sensible way to go, IMO. However, your conversion routines certainly aren't particularly efficient. I would separate out your code into
Parse
andFormat
methods, then theConvert
method can be something like:(You can use a
string
to represent the different bases if you want, of course. If you really need that sort of flexibility though, I'd be tempted to create a new class to represent a "numeric representation". That class should probably be the one to haveParse
,Format
andConvert
in it.)