2

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

vurmux
  • 9,420
  • 3
  • 25
  • 45
Kat Gibson
  • 21
  • 2
  • You could use the zfill function: `str(100111).zfill(8)` or a string format: `'{:0>8}'.format(100111)`. See the answers to [this question](https://stackoverflow.com/questions/16926130/convert-to-binary-and-keep-leading-zeros-in-python). – snakecharmerb Apr 19 '19 at 06:29

2 Answers2

4

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.

vurmux
  • 9,420
  • 3
  • 25
  • 45
0

I wrote a JS function

function getBinary(input) {

    if (input > 255) {
        return "fu";
    }

    //reverse func
    function reverse(s){
        return s.split("").reverse().join("");
    }

    //variable definition
    var rest;
    var temp = 1;
    var str="";
    var zeroeslength;

    //magic
    while (temp > 0) {
    temp = Math.floor(input / 2);
    rest = input - (temp * 2);
    input = temp;
    str = str + rest;
    }
    str = reverse(str);

    //check length
    zeroeslength = 8 - str.length;

    //if length < 8 : add zeroes
    while (zeroeslength > 0) {
        str = 0 + str;
        zeroeslength--;
    }
    
    //output
    return str;
}
  • Welcome to Stack Overflow, notice the OP tagged his question as Python. Please refrain from posting answers with differing languages than the one tagged or asked for by the OP. Mixed answers in a specifically tagged question make it hard for others to find the answers they are looking for. – j__carlson Nov 25 '21 at 03:57