二进制字符串到十进制字符串 [英] Binary String to Decimal String

查看:115
本文介绍了二进制字符串到十进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下午好,

您将如何将具有比一种语言最大的整数类型的位数更多的字符的二进制字符串转换为十进制字符串?换句话说,假设您拥有字符串

How would you go about converting to a decimal string a binary string with more characters than bits in a language's largest integer type? In other words, supposing that you have the string

111001101001110100100(...)1001001111011100100

而您不能先将其转换为整数,那么如何以10为基数写呢?

and that you can't convert it to an integer first, how would you go about writing it in base 10?

非常感谢。

推荐答案

您可以使用以下算法:

// 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'

X的欧几里得除以10是这样计算的:

The Euclidean division of X by 10 is computed like this:

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

这篇关于二进制字符串到十进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆