如何正确地将列表中的二进制字符转换为十进制
我想创建一个函数,它将列表数组中的二进制数转换为十进制数。为此,我反转了列表并使用 for 循环来迭代列表项。但是我无法得到正确的结果。谁能帮助我我在哪里犯了错误?
def binary_array_to_number(arr):
#arr = arr.reverse()
arr = arr [::-1]
new_num = 0
for item in arr:
for i in range(len(arr)):
new_num = new_num+item*(2**i)
print(new_num)
binary_array_to_number(arr= [0, 0, 0, 1])
I want to create a function which will convert the binary numbers in list array to the decimal numbers. For that I have reversed a list and used for loop to iterate the list items. However I am unable to get correct result. Can anyone help me where am I committing the mistake?
def binary_array_to_number(arr):
#arr = arr.reverse()
arr = arr [::-1]
new_num = 0
for item in arr:
for i in range(len(arr)):
new_num = new_num+item*(2**i)
print(new_num)
binary_array_to_number(arr= [0, 0, 0, 1])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 使用
int()
构造函数内置了从二进制到 10 进制数字的转换。通过将数组转换为表示二进制数的字符串,您可以使用int
将其转换为十进制:Python has built-in conversion from binary to base-10 numbers using the
int()
constructor. By converting the array to a string representing the binary number, you can useint
to convert it to decimal:您不会检查当前位是否为
1
,因此您始终会生成2**n - 1
。另外,您运行了两个循环,而不是一个,这也会导致错误的结果。You're not checking if the current bit is
1
or not, so you'll always generate2**n - 1
. Also, you've got two loops running instead of one, which will also lead to an incorrect result.