{"id":52372,"date":"2023-06-30T09:55:35","date_gmt":"2023-06-30T09:55:35","guid":{"rendered":"https:\/\/www.askpython.com\/?p=52372"},"modified":"2023-06-30T09:55:36","modified_gmt":"2023-06-30T09:55:36","slug":"binary-numbers-operations","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/binary-numbers-operations","title":{"rendered":"Binary Numbers and Their Operations in Python &#8211; Complete Guide"},"content":{"rendered":"\n<p>Welcome to this article where we will dive into the world of binary numbers. We will explore their conversions, arithmetic operations, and bitwise operations. Binary numbers are the language that every machine understands. <\/p>\n\n\n\n<p>Every digital data\/media\/system can be dumbed down to binary! Binary numbers have significance in cryptography, low-level programming, and encoding\/decoding. They are the basis of almost all the digital systems today. Let&#8217;s start this journey and expand our knowledge together.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Understanding the Fundamentals of Binary Numbers<\/h2>\n\n\n\n<p>Binary numbers, represented using the base-2 numeral system, are a fundamental concept in digital systems and computer science. The base-2 numeral system uses only two digits to represent any number which is 0 and 1. <\/p>\n\n\n\n<p>In contrast, the decimal numeral system, which we are most familiar with is a base-10 system that uses ten digits (0-9). Learn more about number bases <a href=\"https:\/\/math.libretexts.org\/Courses\/Mount_Royal_University\/MATH_2150%3A_Higher_Arithmetic\/7%3A_Numeration_systems\/7.2%3A_Number_Bases\" target=\"_blank\" rel=\"noopener\">here<\/a>. Some pointers that you should keep in mind while working with binary numbers:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Each digit in a binary number is called a bit. <\/li>\n\n\n\n<li>The rightmost bit represents the value 2^0(=1), the next bit to the left represents 2^1(=2), the next bit represents 2^2(=4), and so on. <\/li>\n\n\n\n<li>Each bit&#8217;s value is obtained by rising 2 to the power of its position from the right and multiplying it by the corresponding bit value (0 or 1). <\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Manual Conversion of Binary to Decimal<\/h3>\n\n\n\n<p>Let&#8217;s consider a smaller binary number with 4 bits, <code>1010<\/code>. To convert this binary number to decimal, we can follow these steps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>To convert a binary number to decimal, assign each digit a weight based on its position from <strong>right to left<\/strong>. The rightmost digit has a weight of 2^0, the next digit has a weight of 2^1, then 2^2, and so on<\/li>\n\n\n\n<li>Multiply each digit by its corresponding weight which means let&#8217;s go from right to left, we have 0 at the extreme right of the binary number so we will multiply 0 by 2^0, after that, we have 1 and then we will multiply will be 2^1 and so on.<\/li>\n\n\n\n<li>Sum up the results: 1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0 * 2^0 = 8 + 0 + 2 + 0 = 10. <\/li>\n\n\n\n<li>Therefore, the binary number 1010 is equal to the decimal number 10.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Python Approach: Decimal to Binary Conversion<\/h2>\n\n\n\n<p>To convert any decimal number to binary you can use <code>bin()<\/code> in python that takes an integer number as an argument and rolls out its binary form. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndecimal_number = 10\nbinary_number = bin(decimal_number)\nprint(binary_number)  \n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"86\" height=\"22\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_5.png\" alt=\"Bin 5\" class=\"wp-image-52432\"\/><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>&#8220;0b&#8221; is a prefix written to indicate that the following number is a binary number. It serves as a visual indicator to differentiate binary numbers from other numerical representations.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\">Python Approach: Binary to Decimal Conversion<\/h2>\n\n\n\n<p>You can convert a binary number to an integer using the <code>int(binary_number,2)<\/code> function by specifying a base of 2. Base 2 corresponds to the binary numbers. Other bases are also present like 10 for decimal and 16 for hexadecimal, you can use  these to convert the respective numerical representation to integers by just modifying the parameter of the int() function.<\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nbinary_number = &#039;1010&#039;\ndecimal_number = int(binary_number, 2)\nprint(decimal_number)  \n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"67\" height=\"26\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_6.png\" alt=\"Bin 6\" class=\"wp-image-52434\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Performing Arithmetic Operations on Binary Numbers in Python<\/h2>\n\n\n\n<p>We can perform basic arithmetic operations on binary numbers just like decimal numbers. However direct arithmetic operation is not possible. Please go through the example below:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Binary addition\nbinary_num1 = &#039;1010&#039;\nbinary_num2 = &#039;1101&#039;\nresult = bin(int(binary_num1, 2) + int(binary_num2, 2))\nprint(result)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"103\" height=\"27\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_1.png\" alt=\"Bin 1\" class=\"wp-image-52431\"\/><\/figure>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<p>To add the binary numbers &#8216;1010&#8217; and &#8216;1101&#8217; we will first convert them into decimal form using int(). Here &#8216;1010&#8217; and &#8216;1101&#8217; will get converted into 10 (i.e. = 1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0 * 2^0) and 13 (i.e. = 1 * 2^3 + 1 * 2^2 + 0 * 2^1 + 1 * 2^0) and after that, we get the final sum 23 represented as 10111.<\/p>\n\n\n\n<p>Similar rules apply to other operations like subtraction, multiplication, and division. Take a glance at the examples below, we are just changing the arithmetic operations but the process to do binary arithmetic is the same:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n # Binary subtraction\nbinary_num1 = &#039;1101&#039;\nbinary_num2 = &#039;1010&#039;\nresult = bin(int(binary_num1, 2) - int(binary_num2, 2))\nprint(result)  \n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"77\" height=\"22\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_2.png\" alt=\"Bin 2\" class=\"wp-image-52430\"\/><\/figure>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Binary multiplication\nbinary_num1 = &#039;1010&#039;\nbinary_num2 = &#039;1101&#039;\nresult = bin(int(binary_num1, 2) * int(binary_num2, 2))\nprint(result)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"126\" height=\"30\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_3.png\" alt=\"Bin 3\" class=\"wp-image-52429\"\/><\/figure>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Binary division\nbinary_num1 = &#039;1101&#039;\nbinary_num2 = &#039;101&#039;\nresult = bin(int(binary_num1, 2) \/\/ int(binary_num2, 2))\nprint(result)  \n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_4.png\" alt=\"Bin 4\" class=\"wp-image-52428\" width=\"106\" height=\"29\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Exploring Bitwise Operations in Python<\/h2>\n\n\n\n<p>In Python, bitwise operations allow you to manipulate individual bits within integers. They are highly used to design circuits and systems. These operations work by performing operations on the binary representations of the numbers. Here are the commonly used bitwise operators in Python:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Bitwise AND<\/h3>\n\n\n\n<p>Bitwise AND (<code>&<\/code>) Performs a bitwise AND operation between the corresponding bits of two numbers. The result has 1s only in the positions where both numbers have 1s. For any other combination (01, 00, 11)we will get a 0. <\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Bitwise AND\nnum1 = 0b1010\nnum2 = 0b1100\nresult = num1 &amp; num2\nprint(bin(result)) \n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"95\" height=\"18\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_7.png\" alt=\"Bin 7\" class=\"wp-image-52435\"\/><\/figure>\n\n\n\n<p>The code will perform a bitwise AND operation on the binary numbers <code>0b1010<\/code> and <code>0b1100<\/code>. The resulting binary number is <code>0b1000<\/code>, which represents the decimal number 8.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>The binary operations are not limited to only two numbers; you can perform the operations on more than two numbers at the same time in one line. This is true for all the operators except the NOT operation.<\/p>\n<\/blockquote>\n\n\n\n<h3 class=\"wp-block-heading\">Bitwise OR<\/h3>\n\n\n\n<p>The bitwise OR operator (<code>|<\/code>) in Python evaluates each bit position and returns a result where each bit is set to 1 if at least one of the corresponding bits in the operands is 1. Possible combinations are 11, 10, and 01. The OR operation returns 0 only if we have a 00.  <\/p>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Bitwise OR\nnum1 = 0b1010\nnum2 = 0b1100\nresult = num1 | num2\nprint(bin(result)) \n<\/pre><\/div>\n\n\n<p>The code will perform a bitwise OR operation on binary numbers <code>0b1010<\/code> and <code>0b1100<\/code>. The result is <code>0b1110<\/code>, which represents the binary number 1110.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_8.png\" alt=\"Bin 8\" class=\"wp-image-52436\" width=\"87\" height=\"27\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Bitwise XOR<\/h3>\n\n\n\n<p>Bitwise XOR (<code>^<\/code>) performs a bitwise XOR (exclusive OR) operation between the corresponding bits of two numbers. The result has 1s in the positions where the bits differ between the two numbers. In a simpler language, if the corresponding bits are same (11 or 00) the result is 0 otherwise the result is 1. If you have interest in problem solving some observations on XOR operation can be really helpful. Let&#8217;s go through the example to understand the python implementation:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Bitwise XOR\nnum1 = 0b110\nnum2 = 0b111\nresult = num1 ^ num2\nprint(bin(result)) \n<\/pre><\/div>\n\n\n<p>The code will perform a bitwise XOR operation on binary numbers <code>0b110<\/code> and <code>0b111<\/code>. The result is <code>0b110<\/code>, which represents the binary number 110.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"82\" height=\"27\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_9.png\" alt=\"Bin 9\" class=\"wp-image-52437\"\/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Bitwise NOT<\/h3>\n\n\n\n<p>Bitwise NOT (<code>~<\/code>) performs a bitwise NOT operation on a <strong>single number<\/strong>, inverting all the bits. This operator flips all the 1s to 0s and vice versa. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Bitwise NOT\nnum = 0b1010\nresult = ~num\nprint(bin(result))  \n<\/pre><\/div>\n\n\n<p>The code applies bitwise NOT (~) to binary 0b1010, resulting in 0b-1011 (two&#8217;s complement). It represents -5 in decimal form by flipping the bits and adding 1.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"96\" height=\"27\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2023\/06\/bin_10.png\" alt=\"Bin 10\" class=\"wp-image-52438\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up: Binary Numbers and Their Operations in Python<\/h2>\n\n\n\n<p>In this article, we&#8217;ve delved into the fascinating world of binary numbers and their operations in Python. From understanding the basics to performing complex bitwise operations, we&#8217;ve seen how Python simplifies working with binary numbers. As we continue to explore Python&#8217;s capabilities, what other intriguing aspects of this language are you excited to uncover?<\/p>\n\n\n\n<p><strong>Below are a few interesting AskPython articles you can go through<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/www.askpython.com\/python\/built-in-methods\/convert-binary-string-to-normal-string\" target=\"_blank\" rel=\"noreferrer noopener\">4 ways to Convert a Binary String to a Normal String.<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/www.askpython.com\/python\/examples\/python-bit-manipulation-masking-techniques\" target=\"_blank\" rel=\"noreferrer noopener\">Python Bit Manipulation and Masking Techniques.<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Welcome to this article where we will dive into the world of binary numbers. We will explore their conversions, arithmetic operations, and bitwise operations. Binary numbers are the language that every machine understands. Every digital data\/media\/system can be dumbed down to binary! Binary numbers have significance in cryptography, low-level programming, and encoding\/decoding. They are the [&hellip;]<\/p>\n","protected":false},"author":56,"featured_media":52447,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-52372","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/52372","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/56"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=52372"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/52372\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/52447"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=52372"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=52372"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=52372"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}