Hoe integers naar binair te converteren in Python 3


Beste antwoord

Dat is het mooie van Python. Veel voorkomende bewerkingen zijn al voor u geïmplementeerd. Dit is zon geval.

U kunt de ingebouwde bin() functie gebruiken. Hier is de beschrijving van bin() Python biedt:

Converteer een geheel getal naar een binaire string. Het resultaat is een geldige Python-expressie. Als x geen Python int -object is, moet het een \_\_index\_\_() -methode die een geheel getal retourneert.

Om het te gebruiken, geeft u gewoon een niet-negatief geheel getal door. Hier zijn enkele voorbeelden van gebruik.

>>> bin(0)

"0b0"

>>> bin(12)

"0b1100"

>>> bin(25)

"0b11001"

>>> bin(250)

"0b11111010"

>>> bin(2440)

"0b100110001000"

Maar misschien wilt u voor leerdoeleinden uw eigen functie implementeren die van decimaal naar binair converteert. In dat geval is hier een beschrijving van het algoritme dat ik heb gebruikt, en hier is mijn implementatie:

def decimal\_to\_binary(decimal):

""" Given a whole, decimal integer,

convert it to a binary

representation

"""

# I"m only making this function support

# non-negative, whole integer only.

if not isinstance(decimal, int) or decimal < 0:

raise TypeError("Input must be a non-negitive, whole integer.")

# we need a stack to store each binary digit in.

stack = []

# while their are still digits left

# to convert in decimal.

while decimal > 0:

# caclute each binary number by dividing decimal

# by two. And since we are "building" our binary

# string backwards, insert() in the front of the

# list instead of append()-ing to the back.

stack.insert(0, str(decimal \% 2))

# after we"ve calcute the binary value of the current

# decimal, divide the decimal by 2. But make sure we

# use // instead of / to get a while number!

decimal = decimal // 2

# join() together each value in stack, and return

# the finished binary string. Note: I simply

# added the "0b" prefix because that is how Python

# prepends its binary strings. If you don"t perfer that,

# then simply remove the "0b" + part from bellow.

return "0b" + "".join(stack)

Tests en gebruik:

>>> bin(0) == decimal\_to\_binary(0)

True

>>> bin(12) == decimal\_to\_binary(12)

True

>>> bin(25) == decimal\_to\_binary(25)

True

>>> bin(250) == decimal\_to\_binary(250)

True

>>> bin(2440) == decimal\_to\_binary(2440)

True

Antwoord

De oplossing van Dripto Biswas is absoluut de snelste. Er zijn echter alternatieve oplossingen, voor het geval u gewoon nieuwsgierig was 🙂

Methode # 2

>>> format(5, "b")

"101"

Methode # 3

>>> "{0:b}".format(5)

"101"

Als u het nu terug wilt converteren,

>>> int("101", 2)

5

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *