二进制字符串到十进制字符串

Mig*_*uel 11 algorithm base

下午好,

你如何将十进制字符串转换成一个二进制字符串,其中包含的字符多于语言最大整数类型中的位数?换句话说,假设你有字符串

111001101001110100100(...)1001001111011100100
Run Code Online (Sandbox Code Playgroud)

并且你不能先将它转换为整数,你将如何在10中写入它?

非常感谢你.

Eri*_*lle 13

您可以使用如下算法:

// X is the input
while ( X != "0" )
  compute X' and R such that X = 10 * X' + R  (Euclidean division, see below)
  output R    // least significant decimal digit first
  X = X'
Run Code Online (Sandbox Code Playgroud)

X乘以10的欧几里德除法计算如下:

R = 0  // remainder in 0..9
X' = ""
for (b in bits of X)  // msb to lsb
  R = 2*R + b
  if R >= 10
    X' += "1"
    R -= 10
  else
    X' += "0"

Remove leading "0" from X'
The remainder is R in 0..9
Run Code Online (Sandbox Code Playgroud)


Sve*_*ach 5

以 10 为基数编写您自己的算术。只需要加法。Python 中的实现示例:

from math import log, ceil

def add(a, b):
    """Add b to a in decimal representation."""
    carry = 0
    for i in range(len(b)):
        carry, a[i] = divmod(a[i] + b[i] + carry, 10)
    while carry:
        i += 1
        carry, a[i] = divmod(a[i] + carry, 10)

# an example string
s = bin(3 ** 120)[2:]

# reserve enough decimal digits
res = [0] * int(ceil(len(s) * log(2) / log(10)))

# convert
for c in s:
    add(res, res)
    if c == "1":
        add(res, [1])

#print output
print str.join("", map(str, reversed(res)))
Run Code Online (Sandbox Code Playgroud)

它使用整数列表来表示以 10 为基数的数字。列表项对应于以 10 为基数的数字。索引 0 处的项目对应于个位,索引 1 处的项目对应于十位,依此类推。


T.E*_*.D. 2

我会使用任意精度数字(bignum)库,例如GMP

GMP 有一个“ gmp_scanf ”函数,可以满足您的要求。

  • 您无法将其转换为 _machine_ 整数,但任意精度的 bignum 不是机器整数(并且不必是整数,顺便说一句)。 (3认同)