簡體   English   中英

如何將二進制數的相應 integer 值打印到其位置? (在蟒蛇中)

[英]How do i print the corresponding integer value of binary number to its place? (in python)

我想找到一個二進制數對應的 integer 值,但要找到它的位值。 我的意思是例如:如果二進制數是 1111,我需要打印 8,4,2,1。

示例 2: 11011 ,output 應該是16,8,2,1。

我是編程新手。 我想不通其中的邏輯。 請幫忙。 謝謝。

n=(bin(int(input("enter number: "))))#i need to find the corresponding place values .
print(n)

我似乎無法弄清楚其中的邏輯。

您可以嘗試以下代碼:

bin_num=bin(11011)

# Convert the binary number to int
int_num = int(bin_num, 2)

# Variable to store the results
text_bin = ""
for ind, character in enumerate(str(int_num)):
    # Get position
    pos = len(str(int_num))-ind-1
    # Suffix
    suffix=","
    if pos==0:
        suffix=""
    # Record position when 1
    if character=="1":
        text_bin+=str(2**pos)+suffix
        
print(text_bin)

Output:

16,8,2,1

您可以通過取以 2 為底的對數來計算數字中 2 的最高冪。 鑒於此信息,只要結果敵人不低於零,就繼續從數字中減去 2 的連續冪。

>>> import math
>>>
>>> parts = []
>>> b = 0b11011
>>> for i in range(int(math.log(b, 2)), -1, -1):
...     c = 2 ** i
...     if (b - c) >= 0:
...         b -= c
...         parts.append(c)
... 
>>> parts
[16, 8, 2, 1]

希望你能理解

n=(bin(int(input("enter number: "))))#i need to find the corresponding place values .

#list to store the binary number separated by each digit
nl = [] 

#A For loop to remove the '0b' in variable n
for i in range(len(n)): 
    if i!=0 and i!=1:
        nl.append(n[i])
    
nl.reverse()

#list to store the answer
al = []

#A for loop to create integer value of each digit
for i in range(len(nl)):
    if nl[i] =='1':
        al.append(2**i)
        
al.reverse()

print(al)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM