Julia Navarro
Julia Navarro

Reputation: 57

0's in the beginning are being skipped & I'm not sure how to fix it

The output value is not including the 0's in the beginning, can someone help me fix the problem?

def bitwiseOR(P, Q):
    return bin(P | Q)

bitwiseOR(0b01010111, 0b00111000)
OUTPUT: '0b1111111'

Upvotes: 0

Views: 68

Answers (2)

David Z
David Z

Reputation: 131640

Leading zeros are a property of the string you produce, not the number. So, for example, if you're looking for a way to make the following two calls produce different results, that's not possible:1

bitwiseOR(0b01010111, 0b00111000)
bitwiseOR( 0b1010111,   0b111000)

However, if you can provide the number of digits separately, then you can do this using the format() function. It accepts a second argument which lets you customize how the number is printed out using the format spec. Based on that spec, you can print a number padded with zeros to a given width like this:

>>> format(127, '#010b')
'0b01111111'

Here the code consists of four pieces:

  • # means apply the 0b prefix at the beginning
  • 0 means pad with leading zeros
  • 10 means the total length of the resulting string should be at least 10 characters
  • b means to print the number in binary

You can tweak the format code to produce your desired string length, or even take the length from a variable.


1Well... technically there is a way to make Python re-read its own source code and possibly produce different results that way, but that's not useful in any real program, it's only useful if you want to learn something about how the Python interpreter works.

Upvotes: 0

Aviv Yaniv
Aviv Yaniv

Reputation: 6298

The leading zeroes are just for representation, so you can utilize Format Specification Mini-Language to display them as you wish:

Format string:

  1. # Includes 0b prefix
  2. 0{length} Pad leading zeroes so total length is length
def bitwiseOR(P, Q, length=10):
    return format(P | Q, f'#0{length}b')

x = bitwiseOR(0b01010111, 0b00111000)
# 0b01111111
print(x)

Upvotes: 1

Related Questions