Invert bits of binary representation of numberBit-twiddling for a custom image formatFinding patterns in a growing collectionMissing element from array (D&C) - code design/aesthetic improvementRotation of elements in an arrayByte array to floating point such as FPE2 in JavaBitfield class and Register depictionSieve of Eratosthenes for small limitsFind the longest length of sequence of 1-bits achievable by flipping a single bit from 0 to 1 in a numberChange Arithmetic Right Shift to Logical Right Shift

Does the United States guarantee any unique freedoms?

Non-OR journals which regularly publish OR research

Improving software when the author can see no need for improvement

Dereferencing a pointer in a 'for' loop initializer creates a segmentation fault

Dropdowns & Chevrons for Right to Left languages

(11 of 11: Meta) What is Pyramid Cult's All-Time Favorite?

Ex-contractor published company source code and secrets online

How would I as a DM create a smart phone-like spell/device my players could use?

Why should we care about syntactic proofs if we can show semantically that statements are true?

English - Acceptable use of parentheses in an author's name

First amendment and employment: Can an employer terminate you for speech?

Am I overreacting to my team leader's unethical requests?

How do I calculate the difference in lens reach between a superzoom compact and a DSLR zoom lens?

Drawing complex inscribed and circumscribed polygons in TikZ

A stranger from Norway wants to have money delivered to me

Ordering a word list

Are there any differences in causality between linear and logistic regression?

Why does Intel's Haswell chip allow FP multiplication to be twice as fast as addition?

Best gun to modify into a monsterhunter weapon?

If a Contingency spell has been cast on a creature, does the Simulacrum spell transfer the contingent spell to its duplicate?

Performance of a branch and bound algorithm VS branch-cut-heuristics

Max Order of an Isogeny Class of Rational Elliptic Curves is 8?

Why is there a need to prevent a racist, sexist, or otherwise bigoted vendor from discriminating who they sell to?

Plausibility of Ice Eaters in the Arctic



Invert bits of binary representation of number


Bit-twiddling for a custom image formatFinding patterns in a growing collectionMissing element from array (D&C) - code design/aesthetic improvementRotation of elements in an arrayByte array to floating point such as FPE2 in JavaBitfield class and Register depictionSieve of Eratosthenes for small limitsFind the longest length of sequence of 1-bits achievable by flipping a single bit from 0 to 1 in a numberChange Arithmetic Right Shift to Logical Right Shift






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








3












$begingroup$


This is the code I came up with.



I added comments to make the solution more verbose.



int findComplement(int num) 
// b is the answer which will be returned
int b = 0;

// One bit will be taken at a time from num, will be inverted and stored in n for adding to result
int n = 0;

// k will be used to shift bit to be inserted in correct position
int k = 0;

while(num)
// Invert bit of current number
n = !(num & 1);

// Shift the given number one bit right to accesss next bit in next iteration
num = num >>1 ;

// Add the inverted bit after shifting
b = b + (n<<k);

// Increment the number by which to shift next bit
k++;

return b;



Is there any redundant statment in my code which can be removed? Or any other better logic to invert bits of a given integer










share|improve this question









$endgroup$









  • 2




    $begingroup$
    Are you re-inventing the binary not operator (~)?
    $endgroup$
    – Martin R
    8 hours ago










  • $begingroup$
    I don't want to sound dumb, But honestly, I did not know that ~ operator existed which inverts all bits of a given integer.
    $endgroup$
    – KshitijV97
    7 hours ago






  • 1




    $begingroup$
    Many easy ways. ~num or -1 - num, or 0xFFFFFFFF - num, or 0xFFFFFFFF ^ num or (-1) ^ num. Doing it one bit at a time is most definitely the hard way.
    $endgroup$
    – AJNeufeld
    6 hours ago

















3












$begingroup$


This is the code I came up with.



I added comments to make the solution more verbose.



int findComplement(int num) 
// b is the answer which will be returned
int b = 0;

// One bit will be taken at a time from num, will be inverted and stored in n for adding to result
int n = 0;

// k will be used to shift bit to be inserted in correct position
int k = 0;

while(num)
// Invert bit of current number
n = !(num & 1);

// Shift the given number one bit right to accesss next bit in next iteration
num = num >>1 ;

// Add the inverted bit after shifting
b = b + (n<<k);

// Increment the number by which to shift next bit
k++;

return b;



Is there any redundant statment in my code which can be removed? Or any other better logic to invert bits of a given integer










share|improve this question









$endgroup$









  • 2




    $begingroup$
    Are you re-inventing the binary not operator (~)?
    $endgroup$
    – Martin R
    8 hours ago










  • $begingroup$
    I don't want to sound dumb, But honestly, I did not know that ~ operator existed which inverts all bits of a given integer.
    $endgroup$
    – KshitijV97
    7 hours ago






  • 1




    $begingroup$
    Many easy ways. ~num or -1 - num, or 0xFFFFFFFF - num, or 0xFFFFFFFF ^ num or (-1) ^ num. Doing it one bit at a time is most definitely the hard way.
    $endgroup$
    – AJNeufeld
    6 hours ago













3












3








3





$begingroup$


This is the code I came up with.



I added comments to make the solution more verbose.



int findComplement(int num) 
// b is the answer which will be returned
int b = 0;

// One bit will be taken at a time from num, will be inverted and stored in n for adding to result
int n = 0;

// k will be used to shift bit to be inserted in correct position
int k = 0;

while(num)
// Invert bit of current number
n = !(num & 1);

// Shift the given number one bit right to accesss next bit in next iteration
num = num >>1 ;

// Add the inverted bit after shifting
b = b + (n<<k);

// Increment the number by which to shift next bit
k++;

return b;



Is there any redundant statment in my code which can be removed? Or any other better logic to invert bits of a given integer










share|improve this question









$endgroup$




This is the code I came up with.



I added comments to make the solution more verbose.



int findComplement(int num) 
// b is the answer which will be returned
int b = 0;

// One bit will be taken at a time from num, will be inverted and stored in n for adding to result
int n = 0;

// k will be used to shift bit to be inserted in correct position
int k = 0;

while(num)
// Invert bit of current number
n = !(num & 1);

// Shift the given number one bit right to accesss next bit in next iteration
num = num >>1 ;

// Add the inverted bit after shifting
b = b + (n<<k);

// Increment the number by which to shift next bit
k++;

return b;



Is there any redundant statment in my code which can be removed? Or any other better logic to invert bits of a given integer







c++ mathematics bitwise






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 8 hours ago









KshitijV97KshitijV97

806 bronze badges




806 bronze badges










  • 2




    $begingroup$
    Are you re-inventing the binary not operator (~)?
    $endgroup$
    – Martin R
    8 hours ago










  • $begingroup$
    I don't want to sound dumb, But honestly, I did not know that ~ operator existed which inverts all bits of a given integer.
    $endgroup$
    – KshitijV97
    7 hours ago






  • 1




    $begingroup$
    Many easy ways. ~num or -1 - num, or 0xFFFFFFFF - num, or 0xFFFFFFFF ^ num or (-1) ^ num. Doing it one bit at a time is most definitely the hard way.
    $endgroup$
    – AJNeufeld
    6 hours ago












  • 2




    $begingroup$
    Are you re-inventing the binary not operator (~)?
    $endgroup$
    – Martin R
    8 hours ago










  • $begingroup$
    I don't want to sound dumb, But honestly, I did not know that ~ operator existed which inverts all bits of a given integer.
    $endgroup$
    – KshitijV97
    7 hours ago






  • 1




    $begingroup$
    Many easy ways. ~num or -1 - num, or 0xFFFFFFFF - num, or 0xFFFFFFFF ^ num or (-1) ^ num. Doing it one bit at a time is most definitely the hard way.
    $endgroup$
    – AJNeufeld
    6 hours ago







2




2




$begingroup$
Are you re-inventing the binary not operator (~)?
$endgroup$
– Martin R
8 hours ago




$begingroup$
Are you re-inventing the binary not operator (~)?
$endgroup$
– Martin R
8 hours ago












$begingroup$
I don't want to sound dumb, But honestly, I did not know that ~ operator existed which inverts all bits of a given integer.
$endgroup$
– KshitijV97
7 hours ago




$begingroup$
I don't want to sound dumb, But honestly, I did not know that ~ operator existed which inverts all bits of a given integer.
$endgroup$
– KshitijV97
7 hours ago




1




1




$begingroup$
Many easy ways. ~num or -1 - num, or 0xFFFFFFFF - num, or 0xFFFFFFFF ^ num or (-1) ^ num. Doing it one bit at a time is most definitely the hard way.
$endgroup$
– AJNeufeld
6 hours ago




$begingroup$
Many easy ways. ~num or -1 - num, or 0xFFFFFFFF - num, or 0xFFFFFFFF ^ num or (-1) ^ num. Doing it one bit at a time is most definitely the hard way.
$endgroup$
– AJNeufeld
6 hours ago










1 Answer
1






active

oldest

votes


















2












$begingroup$

int n = 0; This initialization is not used. It could simply be int n;, or could be int n = !(num & 1); inside the loop, to restrict the scope of n.




This loop:



int k = 0;
while (num)
...
k++;



could be written as:



for(int k = 0; num; k++) 
...




Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:



 b = b | (n << k);


or simply:



 b |= n << k;



Bug



You are not inverting the most significant zero bits. Assuming an 8-bit word size, the binary compliment of 9 (0b00001001) should be 0b11110110, not 0b00000110. And the compliment of that should return to the original number (0b00001001), but instead yields 0b00000001.




And, as mentioned by @Martin R, you could simply return ~num;






share|improve this answer









$endgroup$

















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f225897%2finvert-bits-of-binary-representation-of-number%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2












    $begingroup$

    int n = 0; This initialization is not used. It could simply be int n;, or could be int n = !(num & 1); inside the loop, to restrict the scope of n.




    This loop:



    int k = 0;
    while (num)
    ...
    k++;



    could be written as:



    for(int k = 0; num; k++) 
    ...




    Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:



     b = b | (n << k);


    or simply:



     b |= n << k;



    Bug



    You are not inverting the most significant zero bits. Assuming an 8-bit word size, the binary compliment of 9 (0b00001001) should be 0b11110110, not 0b00000110. And the compliment of that should return to the original number (0b00001001), but instead yields 0b00000001.




    And, as mentioned by @Martin R, you could simply return ~num;






    share|improve this answer









    $endgroup$



















      2












      $begingroup$

      int n = 0; This initialization is not used. It could simply be int n;, or could be int n = !(num & 1); inside the loop, to restrict the scope of n.




      This loop:



      int k = 0;
      while (num)
      ...
      k++;



      could be written as:



      for(int k = 0; num; k++) 
      ...




      Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:



       b = b | (n << k);


      or simply:



       b |= n << k;



      Bug



      You are not inverting the most significant zero bits. Assuming an 8-bit word size, the binary compliment of 9 (0b00001001) should be 0b11110110, not 0b00000110. And the compliment of that should return to the original number (0b00001001), but instead yields 0b00000001.




      And, as mentioned by @Martin R, you could simply return ~num;






      share|improve this answer









      $endgroup$

















        2












        2








        2





        $begingroup$

        int n = 0; This initialization is not used. It could simply be int n;, or could be int n = !(num & 1); inside the loop, to restrict the scope of n.




        This loop:



        int k = 0;
        while (num)
        ...
        k++;



        could be written as:



        for(int k = 0; num; k++) 
        ...




        Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:



         b = b | (n << k);


        or simply:



         b |= n << k;



        Bug



        You are not inverting the most significant zero bits. Assuming an 8-bit word size, the binary compliment of 9 (0b00001001) should be 0b11110110, not 0b00000110. And the compliment of that should return to the original number (0b00001001), but instead yields 0b00000001.




        And, as mentioned by @Martin R, you could simply return ~num;






        share|improve this answer









        $endgroup$



        int n = 0; This initialization is not used. It could simply be int n;, or could be int n = !(num & 1); inside the loop, to restrict the scope of n.




        This loop:



        int k = 0;
        while (num)
        ...
        k++;



        could be written as:



        for(int k = 0; num; k++) 
        ...




        Since you are doing bit manipulation, instead of using addition, you should probably use a “binary or” operation to merge the bit into your accumulator:



         b = b | (n << k);


        or simply:



         b |= n << k;



        Bug



        You are not inverting the most significant zero bits. Assuming an 8-bit word size, the binary compliment of 9 (0b00001001) should be 0b11110110, not 0b00000110. And the compliment of that should return to the original number (0b00001001), but instead yields 0b00000001.




        And, as mentioned by @Martin R, you could simply return ~num;







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 5 hours ago









        AJNeufeldAJNeufeld

        10.9k1 gold badge8 silver badges33 bronze badges




        10.9k1 gold badge8 silver badges33 bronze badges






























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f225897%2finvert-bits-of-binary-representation-of-number%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її