{"id":26615,"date":"2017-12-21T20:41:21","date_gmt":"2017-12-21T15:11:21","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26615"},"modified":"2017-12-21T20:41:21","modified_gmt":"2017-12-21T15:11:21","slug":"c-programming-find-position-set-bit","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-find-position-set-bit\/","title":{"rendered":"C Programming Find position of the only set bit"},"content":{"rendered":"<p>Given a number having only one \u20181\u2019 and all other \u20190\u2019s in its binary representation, find position of the only set bit. Source: Microsoft Interview | 18<br \/>\n<strong>We strongly recommend that you click here and practice it, before moving on to the solution.<\/strong><br \/>\nThe idea is to start from rightmost bit and one by one check value of every bit. Following is detailed algorithm.<\/p>\n<p><strong>1)<\/strong> If number is power of two then and then only its binary representation contains only one \u20181\u2019. That\u2019s why check whether given number is power of 2 or not. If given number is not power of 2, then print error message and exit.<\/p>\n<p><strong>2)<\/strong> Initialize two variables; i = 1 (for looping) and pos = 1 (to find position of set bit)<\/p>\n<p><strong>3)<\/strong> Inside loop, do bitwise AND of i and number \u2018N\u2019. If value of this operation is true, then \u201cpos\u201d bit is set, so break the loop and return position. Otherwise, increment \u201cpos\u201d by 1 and left shift i by 1 and repeat the procedure.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C Programming<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ C program to find position of only set bit in a given number<br\/>#include &lt;stdio.h&gt;<br\/> <br\/>\/\/ A utility function to check whether n is power of 2 or not. See http:\/\/goo.gl\/17Arj<br\/>int isPowerOfTwo(unsigned n)<br\/>{  return n &amp;&amp; (! (n &amp; (n-1)) ); }<br\/> <br\/>\/\/ Returns position of the only set bit in &#039;n&#039;<br\/>int findPosition(unsigned n)<br\/>{<br\/>    if (!isPowerOfTwo(n))<br\/>        return -1;<br\/> <br\/>    unsigned i = 1, pos = 1;<br\/> <br\/>    \/\/ Iterate through bits of n till we find a set bit<br\/>    \/\/ i&amp;n will be non-zero only when &#039;i&#039; and &#039;n&#039; have a set bit<br\/>    \/\/ at same position<br\/>    while (!(i &amp; n))<br\/>    {<br\/>        \/\/ Unset current bit and set the next bit in &#039;i&#039;<br\/>        i = i &lt;&lt; 1;<br\/> <br\/>        \/\/ increment position<br\/>        ++pos;<br\/>    }<br\/> <br\/>    return pos;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main(void)<br\/>{<br\/>    int n = 16;<br\/>    int pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    n = 12;<br\/>    pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    n = 128;<br\/>    pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>n = 16, Position 5\r\nn = 12, Invalid number\r\nn = 128, Position 8<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p>Following is <strong>another method<\/strong> for this problem. The idea is to one by one right shift the set bit of given number \u2018n\u2019 until \u2018n\u2019 becomes 0. Count how many times we shifted to make \u2018n\u2019 zero. The final count is position of the set bit.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C Programming<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ C program to find position of only set bit in a given number<br\/>#include &lt;stdio.h&gt;<br\/> <br\/>\/\/ A utility function to check whether n is power of 2 or not<br\/>int isPowerOfTwo(unsigned n)<br\/>{  return n &amp;&amp; (! (n &amp; (n-1)) ); }<br\/> <br\/>\/\/ Returns position of the only set bit in &#039;n&#039;<br\/>int findPosition(unsigned n)<br\/>{<br\/>    if (!isPowerOfTwo(n))<br\/>        return -1;<br\/> <br\/>    unsigned count = 0;<br\/> <br\/>    \/\/ One by one move the only set bit to right till it reaches end<br\/>    while (n)<br\/>    {<br\/>        n = n &gt;&gt; 1;<br\/> <br\/>        \/\/ increment count of shifts<br\/>        ++count;<br\/>    }<br\/> <br\/>    return count;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main(void)<br\/>{<br\/>    int n = 0;<br\/>    int pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    n = 12;<br\/>    pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    n = 128;<br\/>    pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>n = 0, Invalid number\r\nn = 12, Invalid number\r\nn = 128, Position 8<\/pre>\n<p><strong>We can also use log base 2 to find the position<\/strong>.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C Programming<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include &lt;stdio.h&gt;<br\/> <br\/>unsigned int Log2n(unsigned int n)<br\/>{<br\/>   return (n &gt; 1)? 1 + Log2n(n\/2): 0;<br\/>}<br\/> <br\/>int isPowerOfTwo(unsigned n)<br\/>{<br\/>    return n &amp;&amp; (! (n &amp; (n-1)) );<br\/>}<br\/> <br\/>int findPosition(unsigned n)<br\/>{<br\/>    if (!isPowerOfTwo(n))<br\/>        return -1;<br\/>    return Log2n(n) + 1;<br\/>}<br\/> <br\/>\/\/ Driver program to test above function<br\/>int main(void)<br\/>{<br\/>    int n = 0;<br\/>    int pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    n = 12;<br\/>    pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    n = 128;<br\/>    pos = findPosition(n);<br\/>    (pos == -1)? printf(&quot;n = %d, Invalid number\\n&quot;, n):<br\/>                 printf(&quot;n = %d, Position %d \\n&quot;, n, pos);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>n = 0, Invalid number\r\nn = 12, Invalid number\r\nn = 128, Position 8<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C Programming Find position of the only set bit &#8211; Given a number having only one \u20181\u2019 and all other \u20190\u2019s in its binary representation.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[74852],"tags":[79366,79349,79354,79372,79364,79369,79371,79347,79353,79355,70190,70212,70195,75880,75082,79374,79373,79375,75085,75083,75079,79357,79361,79350,79360,75268,75078,75270,79381,75886,76288,75089,79383,75883,75086],"class_list":["post-26615","post","type-post","status-publish","format-standard","hentry","category-bit-algorithms","tag-assemble","tag-asynchronous-counter","tag-attenuator","tag-attribute","tag-authenticator","tag-autotransformer","tag-babble","tag-bandpass-filter","tag-basel-2","tag-bbs","tag-binary","tag-binary-code","tag-binary-numbers","tag-bit","tag-bit-bit-bit","tag-bit-bit-bit-bit","tag-bit-works","tag-bitmap","tag-bitset","tag-bitwise-operations-in-c","tag-bitwise-operator-in-c","tag-black-body","tag-blink","tag-block-cipher","tag-boost-converter","tag-bytes-table","tag-clearbit","tag-first-in-math-hack","tag-hamming-code-example","tag-html-graphics","tag-logical-shift","tag-nextbit","tag-oral-positions","tag-powers-of-2","tag-xor-operator-in-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26615","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26615"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26615\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26615"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26615"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26615"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}