How to Change the Base in Python

Save

In Python, you can represent numbers in several different bases other than the default decimal, or base-10. However, when you change the base, Python represents these numbers as strings with a prefix to identify the base: "0b" for binary, "0" for octal and "0x" for hexadecimal. If you try to add non-base-10 numbers, Python concatenates the strings. Other calculations result in a type error. To do math on numbers not in base-10, you must convert them to integers, do the calculation, and then convert them back to the original base representation.

  • Open a Python program file. Type the following code:

    print bin(50)

    print oct(50)

    print hex(50)

    These three lines take the decimal number 50 and changes its base first to binary (base-2) and prints "0b110010," then to octal (base-8) and prints "062" and finally to hexadecimal (base-16) and prints "0x32." Note that all three of these values are string representations of their respective bases.

  • Type the following code:

    print 0b11001

    print 031

    print 0x19

    Each of these lines convert the base number to a decimal value. The "0b" in the first line represents a binary number, the "0" in the second represents octal and the "0x" in the third line represents a hex value. Each number, 11001 in binary, 31 in octal and 19 in hexadecimal, converts to 25 in decimal.

  • Type the following code:

    var1 = bin(25)

    var2 = bin(50)

    bin(int(var1,2) + int(var2,2))

    The first two lines create two variables to hold the binary representations of the decimal numbers 25 and 50, respectively. The third line converts each binary number to an integer, adds their values together, then converts the number back to a binary representation. The output here is "0b1001011," which is the binary equivalent of 75 in decimal.

References

Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!