top of page

Binary <==> Decimal Conversion

Binary to Decimal Conversion of numbers uses weighted columns to identify the order of the digits to determine the final value of the number => https://www.electronics-tutorials.ws/binary/bin_2.html

For example,

1011 = 1*2^3 + 0*2^2 + 1*2^1 + 1*2^0 = 8+0+2+1 = 11

1000= 1*2^3 + 0*2^2 + 0*2^1 + 0*2^0 = 8+0+0+0 = 8

In Python, there is a trick when we print converted binary to decimal, the trick is add Prefix 0b (0 is zero) before the binary:

print(0b1011) => 11

print(0b1000) => 8

print(0b1011000) => 88

For octal, the prefix is 0o. For hexadecimal, the prefix is 0x.

Now, what about the other way around? convert decimal to binary?

so try,

print(bin(11)),

print(bin(8)),

print(bin(88))

To convert to octal, using oct() function.

To convert to hexadecimal, using hex() function.

 

A more explicit way for the conversion is to use int() function, the syntax is

int(x, base)

=> https://www.w3resource.com/python/built-in-function/int.php. But there are several things we need to know.

First, x can be a number or a string. In our case, in fact, it has to be string, as when we convert, we need to put prefix0b all together into parenthesis. And "b" is a letter.

Second, base is Number format. Default value is 10, which is decimal. In our case, the base should be 2, as it is binary.

so try,

print(int("0b1001111",2)) => 79

print(int("0b1011",2)) => 11

In the same way, we can convert octal and hexadecimal.

 

Sejal Jaiswal wrote a very good article for Python Data Type Conversion => https://www.datacamp.com/community/tutorials/python-data-type-conversion

aboutME

I am John Fan Zhang, a data analyst and finance researcher. I hold a PhD in finance, CFA charter and full membership of CFA New Zealand Society. I have fifteen-year experience in corporate investment and eight-year experience in advanced data analysis. My research focuses on the effect of social psychology (culture) on financial decisions. Finance research involves heaps of data analyses that lead me to the data field. I am a Microsoft Certified Solutions Expert (MCSE): Data Management and Analytics (Excel, Power BI, and SQL). Aside from Excel, Power BI and SQL, I am also familiar with econometric tools such as Stata, Eviews, and MATLAB. I use OX and Python for programming. I am an active data community event participant, volunteer, speaker, moderator, program reviewer, including PASS Marathon 2020, Global AI BootCamp Auckland 2019, SQL Saturday Auckland (2017, 2018, 2019), and Definity Conference (2018, 2019, 2020, Auckland, New Zealand).

Auckland, New Zealand

  • Google Site
  • Twitter
  • LinkedIn

©2016 BY JOHN'S DATA STORY

bottom of page