Converting Decimal to Binary, how to get 8-bit binary?

点点圈 提交于 2020-11-29 09:49:19

问题


So I need to convert decimal to binary but all of my returns need to be 8 bits long.

I've already figured out the conversion itself but I need to figure out how to add zero's to the beginning if it's less than 8 bits.

old_number = int(input("Enter whole number here: "))
number = old_number
binary_translation = 0

while number > -1:
    if number > 128 or number == 128:
        binary_translation = binary_translation + 10000000
        number = number - 128
    elif number > 64 or number == 64:
        binary_translation = binary_translation + 1000000
        number = number - 64
    elif number > 32 or number == 32:
        binary_translation = binary_translation + 100000
        number = number - 32

etc all the way zero...

print("The number", old_number, "is", binary_translation, "in binary.")

Result I want if number = 39 - 00100111

Result I get if number = 39 - 100111


回答1:


TLDR: Use it: '{:0>8}'.format(str(bin(a))[2:])


You make unnecessary binary transformations. Python have built-in function bin() that can do it for you:

>>> number = 39
>>> bin(number) 

'0b100111'

You can crop it:

>>> str(bin(number))[2:]

'100111'

And add forward zeros:

>>> '{:0>8}'.format(str(bin(a))[2:])

'00100111'

Here is the final one-liner for you: '{:0>8}'.format(str(bin(a))[2:])

If you want to learn more about this: '{:0>8}' magic, you can read this article.



来源:https://stackoverflow.com/questions/55754130/converting-decimal-to-binary-how-to-get-8-bit-binary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!