value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range (int(value)):
prod = ((int(value[*right most digit here*])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
I am trying to create a binary calculator.
I believe I have the power part of the equation working as it begins with 2 ^ 0, then 2 ^ 1 for the next digit and so on. But I am having trouble getting the first part of the equation, the right most digit of the value inputted.
So let's say, 0101 was inputted. I want 1 * ( 2 ^ 0 ) in the first loop, 0 * ( 2 ^ 1) in the second loop, and so on; right to left. So with how indexing works in Python, how can I reverse index it so [4] is in the first loop, then [3] in the second loop, and so on.
Thanks for help.
答案 0 :(得分:0)
实现这一目标的更简单方法是将base
设为int()
为2。例如:
>>> num = '110'
>>> int(num, 2)
6
如果您正在寻找自定义解决方案,您可以创建一个函数:
def binary_string_to_int(binary_string):
int_num = 0
for i in binary_string:
int_num += int(i)
int_num *= 2
return int_num / 2
示例运行:
>>> binary_string_to_int('111')
7
>>> binary_string_to_int('101')
5
答案 1 :(得分:0)
您的代码中存在一些错误,因此请将其替换为:
value = input("Enter the binary value to convert to a decimal number: ")
value = int(value) # conversion from string to number
power = 0
ans = 0
while(value > 0):
lastDigit = value % 10 # last digit
value = value // 10 # cutting off last digit (for next iteration)
prod = lastDigit * (2 ** power)
ans = prod + ans
power = power + 1
print (ans)
最后一位数被计算为除以10之后的余数(value % 10
)
并且整数除以10(value // 10
) - 与基础学校的一年级一样:27 % 10 = 7
27 // 10 = 2
答案 2 :(得分:0)
value = input("Enter the binary value to convert to a decimal number.")
power = 0
ans = 0
for i in reversed(value):
prod = int(i) * (2**power)
ans = prod + ans
power += 1
else:
print(ans)
改进代码,同时尽可能保持代码尽可能接近代码。你的for循环正在创建一个1 to whatever the value we input
的列表,这不是你应该做的。一种方法是将输入视为一个字符串(基本上是一个可以迭代的列表)反转它,这样你就可以从右到左,然后对每个值进行操作。您试图获取值输入位置的索引吗?为什么? Python非常漂亮,你很可能不需要直接告诉索引。
value = input("Enter the binary value to convert to a decimal number.")
prod = 0
power = 0
ans = 0
for i in range(int(len(value))-1):
prod = ((int(value[-1])) * ((2**power)))
ans = prod + ans
prod = 0
power + 1
else:
print (ans)
您正在执行值的范围而不是输入len,因此我们使用len()
来获取输入的字符串的长度。 -1
是因为输入001
的字符串长度可以是3,但如果索引3超出范围,因为索引从0开始而不是1
请注意,在Python中,接受负索引值。负指数意味着从列表的末尾开始并向后计数,所以我认为这是您正在寻找的答案。
例如,如果我们有列表my_list=['a','b','c']
并且我们致电my_list[-2]
,则会返回'b'
答案 3 :(得分:0)
然而,有更好的选择,我假设你正在清除你的基础知识。以下可以是选项:
注意:你应该在循环中使用len(value)而不是int(value)。
# 1. When starting the loop from 0 (i.e. i=0). you can use ( len(value) - i )th index.'
for i in range (len(value)):
prod = ((int(value[len(value) - i - 1])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 2. Python also supports negative indexing, So you may run a loop from -1 to -len(value).
for i in range (-1,-len(value) - 1,-1):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 3. You can reverse the whole string in your first step and then loop from 0 to len(value)-1.
value = reversed(value)
for i in range (len(value)):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
但是代码中存在一些错误(或者可能缺少信息)。此代码仅适用于无符号整数。如果您希望它也可以使用带符号的数字,则必须考虑2的补码。 下面是一个非常简单的代码,也可以使用带符号的数字(如果需要):
#convert binary string into decimal value. Works on 2's complement.
def binToDecimal(s):
neg = False
if s[0] == '1':
s = twosComp(s)
neg = True
#compute the decimal value
val = reduce(lambda x,y : int(x)*2+1 if y=='1' else int(x)*2,'0'+s)
#negate the value if the first bit is 1
return -val if neg else val
#return the 2's complement string
def twosComp(s):
s = list(s[::-1])
#take 1's complement
s = ['1' if i=='0' else '0' for i in s]
#take 2's complement
for i in range(len(s)):
if s[i] == '0':
#no carry will be generated in this case, so we break it.
s[i] = '1'
break
else:
s[i]='0'
# return 2's complement string
return ''.join(map(str,s))[::-1]