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
'sudo apt-get update' get a warning
Who are these characters/superheroes in the posters from Chris's room in Family Guy?
Is refreshing multiple times a test case for web applications?
Was this a rapid SCHEDULED disassembly? How was it done?
Write an interpreter for *
How do we avoid CI-driven development...?
Is it incorrect to write "I rate this book a 3 out of 4 stars?"
Double blind peer review when paper cites author's GitHub repo for code
What does Apple mean by "This may decrease battery life"?
sed delete all the words before a match
Acceptable to cut steak before searing?
Optimal way to extract "positive part" of a multivariate polynomial
Team goes to lunch frequently, I do intermittent fasting but still want to socialize
Dropdowns & Chevrons for Right to Left languages
How do I explain to a team that the project they will work on for six months will certainly be cancelled?
Non-OR journals which regularly publish OR research
Why level 0 espers are considered espers if they have no powers at all?
Why should we care about syntactic proofs if we can show semantically that statements are true?
Why are the inside diameters of some pipe larger than the stated size?
(11 of 11: Meta) What is Pyramid Cult's All-Time Favorite?
In a topological space if there exists a loop that cannot be contracted to a point does there exist a simple loop that cannot be contracted also?
Ex-contractor published company source code and secrets online
How can you evade tax by getting employment income just in equity, then using this equity as collateral to take out loan?
If a Contingency spell has been cast on a creature, does the Simulacrum spell transfer the contingent spell to its duplicate?
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;
$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
c++ mathematics bitwise
$endgroup$
add a comment |
$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
c++ mathematics bitwise
$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
8 hours ago
1
$begingroup$
Many easy ways.~num
or-1 - num
, or0xFFFFFFFF - num
, or0xFFFFFFFF ^ num
or(-1) ^ num
. Doing it one bit at a time is most definitely the hard way.
$endgroup$
– AJNeufeld
7 hours ago
add a comment |
$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
c++ mathematics bitwise
$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
c++ mathematics bitwise
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
8 hours ago
1
$begingroup$
Many easy ways.~num
or-1 - num
, or0xFFFFFFFF - num
, or0xFFFFFFFF ^ num
or(-1) ^ num
. Doing it one bit at a time is most definitely the hard way.
$endgroup$
– AJNeufeld
7 hours ago
add a comment |
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
8 hours ago
1
$begingroup$
Many easy ways.~num
or-1 - num
, or0xFFFFFFFF - num
, or0xFFFFFFFF ^ num
or(-1) ^ num
. Doing it one bit at a time is most definitely the hard way.
$endgroup$
– AJNeufeld
7 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
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
8 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
7 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
7 hours ago
add a comment |
1 Answer
1
active
oldest
votes
$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;
$endgroup$
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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;
$endgroup$
add a comment |
$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;
$endgroup$
add a comment |
$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;
$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;
answered 5 hours ago
AJNeufeldAJNeufeld
10.9k1 gold badge8 silver badges33 bronze badges
10.9k1 gold badge8 silver badges33 bronze badges
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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
8 hours ago
1
$begingroup$
Many easy ways.
~num
or-1 - num
, or0xFFFFFFFF - num
, or0xFFFFFFFF ^ num
or(-1) ^ num
. Doing it one bit at a time is most definitely the hard way.$endgroup$
– AJNeufeld
7 hours ago