如何正确地将列表中的二进制字符转换为十进制

发布于 2025-01-12 00:08:09 字数 406 浏览 0 评论 0原文

我想创建一个函数,它将列表数组中的二进制数转换为十进制数。为此,我反转了列表并使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雾里花 2025-01-19 00:08:09

Python 使用 int() 构造函数内置了从二进制到 10 进制数字的转换。通过将数组转换为表示二进制数的字符串,您可以使用 int 将其转换为十进制:

binary_arr = [0, 0, 0, 1]
binary_string = ''.join(str(digit) for digit in binary_arr)  # this line simply converts the array to a string representing the binary number [0, 0, 0, 1] -> '0001'
decimal_number = int(binary_string, 2)  # the 2 here represents the base for the number - base 2 means binary.
print(decimal_number)  # prints '1'

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 use int to convert it to decimal:

binary_arr = [0, 0, 0, 1]
binary_string = ''.join(str(digit) for digit in binary_arr)  # this line simply converts the array to a string representing the binary number [0, 0, 0, 1] -> '0001'
decimal_number = int(binary_string, 2)  # the 2 here represents the base for the number - base 2 means binary.
print(decimal_number)  # prints '1'
所有深爱都是秘密 2025-01-19 00:08:09

您不会检查当前位是否为 1,因此您始终会生成 2**n - 1。另外,您运行了两个循环,而不是一个,这也会导致错误的结果。

def binary_array_to_number(arr):
     #arr = arr.reverse()
    arr = arr [::-1] 
    new_num = 0
    for i in range(len(arr)):
        if arr[i]:
            new_num += (2**i)
    print(new_num)
binary_array_to_number(arr= [0, 1, 0, 1])

You're not checking if the current bit is 1 or not, so you'll always generate 2**n - 1. Also, you've got two loops running instead of one, which will also lead to an incorrect result.

def binary_array_to_number(arr):
     #arr = arr.reverse()
    arr = arr [::-1] 
    new_num = 0
    for i in range(len(arr)):
        if arr[i]:
            new_num += (2**i)
    print(new_num)
binary_array_to_number(arr= [0, 1, 0, 1])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文