C++ 以 10 为基数到以 n 为基数的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12713999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:33:23  来源:igfitidea点击:

Base 10 to base n conversions

c++algorithmbase-conversion

提问by Rontogiannis Aristofanis

I'm trying to write a C++ program that does base-conversions.

我正在尝试编写一个进行基本转换的 C++ 程序。

I want to convert a decimal number to all the other integer bases from 2 to 20.

我想将一个十进制数转换为从 2 到 20 的所有其他整数基数。

Is there an efficient and easy-to-implement algorithm for base conversions?

是否有一种高效且易于实现的基数转换算法?

回答by penelope

I don't understand where exactly is the problem? It's very easy and straigtforward to do base conversion: you do it as you would by hand.

我不明白问题究竟出在哪里?进行基数转换非常简单和直接:您可以像手工一​​样进行。

  • divide the numberby base
  • write down the remainder
  • repeat the process with the integer part of the division
  • stop when you reach zero
  • the remainders in reverse order give you the digits in base
  • 划分
  • 写下剩下的
  • 用除法的整数部分重复这个过程
  • 当你达到零时停止
  • 以相反顺序的余数为您提供基数中的数字

Example:

例子:

1025 (decimal) to base 15:

1025(十进制)到基数 15:

1025 / 15 = 68 , remainder 5
68   / 15 =  4 , remainder 8
4    / 15 =  0 , remainder 4

The number in base 15 is 485

以 15 为底的数字是 485

回答by Ben Voigt

You may have two problems:

你可能有两个问题:

  • Parsing from the original base to the computer's native integer representation (strtolis quite good at this).

  • Formatting into the new base. (itoais quite good at this).

  • 从原始基数解析为计算机的本机整数表示(strtol在这方面非常擅长)。

  • 格式化到新的基地。(itoa在这方面非常擅长)。

If you want to write it yourself, you might like the divfunction. You feed in the number and the base, and it splits off the rightmost digit. Repeat to get all digits.

如果你想自己写,你可能会喜欢这个div函数。你输入数字和基数,它会从最右边的数字中分离出来。重复以获取所有数字。

If you want to be more efficient, you can divide by the base squared, and get two digits at a time (use a lookup table to get the ASCII characters for both digits). Here's an example of some very efficient implementations.Changing it to use a different base would not be difficult.

如果你想更有效,你可以除以基数平方,一次得到两个数字(使用查找表来获取两个数字的 ASCII 字符)。 下面是一些非常有效的实现示例。改变它以使用不同的基数并不困难。