 # Zero-padding a decimal-to-binary converter in Python

Hello, so I have been given a programming exercise that I find tricky and confusing, as I’m learning how to code in Python. I hope I can get some guidance, I have messed around with codeacademy and w3schools trying to figure out what to do.

”Write a Python procedure (a function that doesn’t return a value) which converts a given decimal number into binary form and defines how many bits or bytes it can be placed into. Then, write a main program that can take the decimal integer and then calls the procedure with the input as a parameter. You will not use any built-in functions to convert the given decimal number for this task. The final program should only handle positive integers (up to 65 535). If the integer is bigger than 255 the output should be presented in 16 bits, and in 8 bits if smaller than 256.”

My code looks like this:

``````
## start of main program

print('Decimal to binary converter.')

def dec2bin(val):
if val > 1:
dec2bin(val // 2)
print(val % 2, end = '')

### end of procedure

val_in_ok = False
val_in = 0

while val_in_ok is False:
val_in = int(input("Enter an integer: "))
if val_in > 65535:
print('Error: Can’t handle numbers that big. Try again.')
elif val_in < 0:
print('Error: Can only handle positive integers. Try again.')
else:
val_in_ok = True
if val_in < 256:
print('The number', val_in ,'fits into 8 bit is in binary form:' )
dec2bin(val_in)

else:
print('The number', val_in ,' fits into 8 bit is in binary form:, ')
dec2bin(val_in)

## end of program
``````

My issue here is that I can’t get the binary number to be written in 8 or 16 bit.
I.E, if I enter 5 as an integer, I want it to spell out 00000101 instead of just 101 like it does now.

Does any friendly soul have the knowledge on how to proceed?

You could store the bits in a list instead of writing them out directly, and then prepend the appropriate number of zeroes (depending on the length of the list) when writing out the number.

Handling the list will be easier if you change the `dec2bin()` function to use a loop instead of recursion.

1 Like

I see, thanks! Do I only have to change the function and leave the part below be in order for this to work? Still a newbie to Python so I need to read a bit more about store them in a list, I talked to a tutor in this online course and received the following hint:

``````def for_bit_pos_msb_to_lsb(value, bit_pos):
if bit_pos >= 0:
if (1 << bit_pos) & value != 0:
# bit_pos is set
else:
# bit_pos is not set
for_bit_pos_msb_to_lsb(value, bit_pos - 1)
``````

Although I’m not sure how to implement it in my current code.

You only have to change the `dec2bin()` function.

With the bit shift and bit-wise “and” that hint has a better way to determine if a certain bit of the `value` is set (did they explain those bit-wise operations already?), which works for any position (`bit_pos`) instead of in a fixed order. I’d still recommend using that with a loop instead of recursively.

Because the task says to use 16 bit at most, you could do something like this:

``````bits = list()
for i in range(16):
if (1 << bit_pos) & value != 0:
bits[i] = 1
else:
bits[i] = 0
``````

That way the list will have all your bits, in order. Note that this way the highest bit will be last in the list, so if you want to print by iterating over the list elements you might want to reverse it first.

I see, thanks! Actually, it was a tutor giving a hint about bit-wise operation but we haven’t learned them yet, so that’s why I’m not getting anywhere at the moment…I guess need to go back to learn a bit more about how to implement it in my current code so that it adjusts for 8 bit and the reverse method.

For the bit-wise operations:

• `1 << bit_pos` is a bit-wise left shift. For example, a left shift by 1 turns binary 1 into 10, a shift of 1 by 2 would lead to 100. In this context, shifting lets you easily create an integer where exactly one bit is set, at the position you want.
• `x & value` is a bit-wise AND. The result will have all bits set that are set in both operands. For example, `101 & 100` will lead to `100` (all binary).

Combining those two as in the example lets you check “is bit number `bit_pos` set in my `value`?”

I don’t think you need a separate version for the 8 bit version, you can just check if the highest 8 bits (of the 16) are all zeroes, and if so output only the lower 8.

1 Like