{"id":7449,"date":"2022-09-08T20:21:17","date_gmt":"2022-09-08T14:51:17","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/"},"modified":"2022-09-08T20:21:17","modified_gmt":"2022-09-08T14:51:17","slug":"solved-two-complements-python-with-as-least-bits-as-possible","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/","title":{"rendered":"[Solved] Two Complement&#8217;s Python (with as least bits as possible)"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-40365873\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"40365873\" data-parentid=\"40365470\" data-score=\"4\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>Here&#8217;s a way to do this using the <code>.bit_length<\/code> method of Python 3 integers. It also uses the string <code>.format<\/code> method to do the integer to binary string conversion. This function returns a string starting with &#8216;0&#8217; for non-negative numbers so that they can be distinguished from negative numbers.<\/p>\n<pre><code>def twos_complement(n):\n    m = n + 1 if n &lt; 0 else n\n    bitlen = 1 + m.bit_length()\n    mask = (1 &lt;&lt; bitlen) - 1\n    return '{0:0{1}b}'.format(n &amp; mask, bitlen)\n\nfor i in (-10, -3, 0, 3, 10):\n    print('{:3}: {}'.format(i, twos_complement(i)))\n\nprint('- ' * 30)\n\nfor i in range(-15, 16):\n    print(i, twos_complement(i))    \n<\/code><\/pre>\n<p><strong>output<\/strong><\/p>\n<pre><code>-10: 10110\n -3: 101\n  0: 0\n  3: 011\n 10: 01010\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \n-15 10001\n-14 10010\n-13 10011\n-12 10100\n-11 10101\n-10 10110\n-9 10111\n-8 1000\n-7 1001\n-6 1010\n-5 1011\n-4 100\n-3 101\n-2 10\n-1 1\n0 0\n1 01\n2 010\n3 011\n4 0100\n5 0101\n6 0110\n7 0111\n8 01000\n9 01001\n10 01010\n11 01011\n12 01100\n13 01101\n14 01110\n15 01111\n<\/code><\/pre>\n<hr>\n<h3>How it works<\/h3>\n<p>Python uses a modified form of two&#8217;s complement to represent integers. Python integers have no size limit, so negative integers behave as if they have an <em>infinite<\/em> number of leading 1 bits, as explained in the <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/wiki.python.org\/moin\/BitwiseOperators\">Python Wiki article on Bitwise Operators<\/a>.<\/p>\n<p>The <code>int.bit_length<\/code> method tells us the minimum number of bits required to represent a number, we want one more bit than that so that all our non-negative numbers will start with 0 and all the negative numbers start with a 1. We need to modify that slightly to ensure that numbers of the form <code>-2**n<\/code> will only get a single leading one bit, we do that by adding 1 to all the negative numbers when calculating the bit length. <\/p>\n<p>To select the bits we want we need a bit mask of the appropriate length. If the bit length is 4, we want a mask of 1111 = <code>2**4 - 1<\/code>; we _could calculate it by using exponentiation, but it&#8217;s more efficient to use bit shifting: <code>(1 &lt;&lt; bitlen) - 1<\/code>. We then do the bitwise AND operation <code>n &amp; mask<\/code> to select the bits we want. Fortunately, Python gives us a non-negative number when we perform such masking operations. \ud83d\ude42<\/p>\n<p>Finally we convert the resulting integer to a string using the <code>.format<\/code> method. We use a nested format specification so we can dynamically specify the correct length of the output string. In <\/p>\n<pre><code>'{0:0{1}b}'.format(n &amp; mask, bitlen) \n<\/code><\/pre>\n<p>the first 0 of the format spec says that we&#8217;re converting the value of the 0 arg in the argument list (<code>n &amp; mask<\/code>), the <code>:0{1}b<\/code> says to convert it to binary, padded with leading zeroes if necessary, using the value of the 1 arg in the argument list (<code>bitlen<\/code>) as the total string length.<\/p>\n<p>You can read about nested format specs in the <a rel=\"nofollow noopener\" target=\"_blank\" href=\"https:\/\/docs.python.org\/3\/library\/string.html#format-string-syntax\">Format String Syntax<\/a> section of the docs:<\/p>\n<blockquote>\n<p>A <em>format_spec<\/em> field can also include nested replacement fields<br \/>\n  within it. These nested replacement fields may contain a field name,<br \/>\n  conversion flag and format specification, but deeper nesting is not<br \/>\n  allowed. The replacement fields within the <em>format_spec<\/em> are<br \/>\n  substituted before the <em>format_spec<\/em> string is interpreted. This<br \/>\n  allows the formatting of a value to be dynamically specified.<\/p>\n<\/blockquote><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">3<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Two Complement&#8217;s Python (with as least bits as possible) <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] Here&#8217;s a way to do this using the .bit_length method of Python 3 integers. It also uses the string .format method to do the integer to binary string conversion. This function returns a string starting with &#8216;0&#8217; for non-negative numbers so that they can be distinguished from negative numbers. def twos_complement(n): m = n &#8230; <a title=\"[Solved] Two Complement&#8217;s Python (with as least bits as possible)\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\" aria-label=\"More on [Solved] Two Complement&#8217;s Python (with as least bits as possible)\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[679,349,482],"class_list":["post-7449","post","type-post","status-publish","format-standard","hentry","category-solved","tag-binary","tag-python","tag-python-3-x"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Two Complement&#039;s Python (with as least bits as possible) - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Two Complement&#039;s Python (with as least bits as possible) - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] Here&#8217;s a way to do this using the .bit_length method of Python 3 integers. It also uses the string .format method to do the integer to binary string conversion. This function returns a string starting with &#8216;0&#8217; for non-negative numbers so that they can be distinguished from negative numbers. def twos_complement(n): m = n ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-08T14:51:17+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Two Complement&#8217;s Python (with as least bits as possible)\",\"datePublished\":\"2022-09-08T14:51:17+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\"},\"wordCount\":411,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"binary\",\"python\",\"python-3.x\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\",\"name\":\"[Solved] Two Complement's Python (with as least bits as possible) - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-08T14:51:17+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Two Complement&#8217;s Python (with as least bits as possible)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Two Complement's Python (with as least bits as possible) - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Two Complement's Python (with as least bits as possible) - JassWeb","og_description":"[ad_1] Here&#8217;s a way to do this using the .bit_length method of Python 3 integers. It also uses the string .format method to do the integer to binary string conversion. This function returns a string starting with &#8216;0&#8217; for non-negative numbers so that they can be distinguished from negative numbers. def twos_complement(n): m = n ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/","og_site_name":"JassWeb","article_published_time":"2022-09-08T14:51:17+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Two Complement&#8217;s Python (with as least bits as possible)","datePublished":"2022-09-08T14:51:17+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/"},"wordCount":411,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["binary","python","python-3.x"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/","url":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/","name":"[Solved] Two Complement's Python (with as least bits as possible) - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-08T14:51:17+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-two-complements-python-with-as-least-bits-as-possible\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Two Complement&#8217;s Python (with as least bits as possible)"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1776403586","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/7449","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=7449"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/7449\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=7449"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=7449"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=7449"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}