Check whether the number has alternating bits? - c++

I have come across the question in leetcode on checking whether the number has alternative bits or not ?. Clear explanation of the question is given below. And this question is solved in stack overflow too. Stackoverflow Solution.
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.Leetcode Question
I know how to solve the question using for loop by checking whether two bits are same or not (i.e previous bit and the present bit is same or not). But i was intrigued by the below solution in leetcode
(n & (n >> 1)) == 0 && (n & (n >> 2)) == (n >> 2)
I am concerned about the understanding behind this one line code. Examples please !!

Lets start with n & (n >> 1) == 0: if the bits are alternating, then there would be 0 overlap, and so & would return 0.
The second part makes sure that the bits aren't all 0 and ensures the last bits which are discarded with the shift are still consistent

Related

Checking overflow for addc function

I am coding a C++ program to simulate a 16 bit virtual machine. I have a function 'addc' in which I have to check for overflow. I'm a little lost on the conditions for overflow. I know overflow happens when you add 2 positive numbers and you get a negative number, or when you add 2 negative numbers and you get a positive number. However, in my function addc, I have 3 numbers I have to add. Am I approaching this correctly?
My function is supposed to do this:
register destination = register destination + register source + carry bit
(rd = rd + rs + c)
So far for checking overflow, I have this code..
//Check when adding positive numbers gives negative result
//My carry bit is always positive (either 0 or 1)
if(rd >= 0 and rs >= 0 and c >= 0) and ((rd + rs + c) < 0)){
//set overflow bit
}
else if( rd < 0 and rs < 0 and c < 0) and (rd + rs + c) > 0) ){
//set overflow bit
}
My confusion is for the else if condition. C will always be 0 or 1, so it'll never go into the else if loop, so there's almost no reason to have the else if loop. Am I doing this right? Or would I have to add the carry bit (c) to one of the operands (either rd or rs) so I only have two operands to compare. Like this?
else if( rd < 0 and ((rs + c) < 0)) and (rd + (rs + c)) > 0) ){
//set overflow bit
}
The fact that your second if statement seems to be operating under the impression that the carry bit could possibly be negative should be the first clue that something doesn't add up (as Foghorn Leghorn would say, "Hey, I think I just made a funny!").
The right way to do this is to simplify the case of a single add operation of three values into two separate add operations. First, add rd and rs, and check for overflow using the conditions you've already defined. Then, take the result of the first addition, and add it to the carry bit, and check for overflow here. The second overflow check can be very simple, given that the carry bit will be either 0, or 1.
The final result will set the overflow bit if either the first or the second add operation was determined to have overflowed.

Bitwise NOT operator returning unexpected and negative value? [duplicate]

This question already has answers here:
Why is the output -33 for this code snippet
(3 answers)
Closed 9 years ago.
I'm trying to get the value of an integer using Bitwise NOT, but i'm not getting what i expected.
#include <stdio.h>
int main(){
int i = 16;
int j = ~i;
printf("%d", j);
return 0;
}
Isn't 16 supposed to be:
00000000000000000000000000010000
So ~16 is supposed to be:
11111111111111111111111111101111
Why i'm not getting what i expected and why the result is negative?
This is what i'm trying to do:
I have a number for exemple 27 which is:
00000000000000000000000000011011
And want to check every bit if it's 1 or 0.
So i need to get for exemple this value
11111111111111111111111111110111
The use second one to check if the 3rd bit of the first is set to 1.
Although there are pedantic points which can be made about compiler behaviour, the simple answer is that a signed int with the top bit set is a negative number.
So if you do something which sets the top bit of an int (a signed int, not an unsigned one), then ask the tools/library to show you the value of that int, you'll see a negative number.
This is not a universal truth, but it's a good approximation to it for most modern systems.
Note that it's printf which is making the representation here - because %d formats numbers as signed. %u may give the result you're expecting. Just changing the types of the variables won't be enough, because printf doesn't know anything about the types of its arguments.
I would say that as a general rule of thumb, if you're doing bit-twiddling, then use unsigned ints and display them in hexadecimal. Life will be simpler that way, and it most generally fits with the intent. (Fancy accelerated maths tricks are an obvious exception)
And want to check every bit if it's 1 or 0.
To check an individual bit, you don't NOT the number, you AND it with an appropriate bit mask:
if ((x & 1) != 0) ... // bit 0 is 1
if ((x & 2) != 0) ... // bit 1 is 1
if ((x & 4) != 0) ... // bit 2 is 1
if ((x & 8) != 0) ... // bit 3 is 1
...
if ((x & (1 << n)) != 0) ... // bit n is 1
...
if ((x & 0x80000000) != 0) ... // bit 31 is 1
If you want to get ones' complement of a number, you need to put that number into an unsigned variable and show it as so.
In C it would be:
unsigned int x = ~16;
printf("%u\n", x);
and you will get 4294967279.
But if you are just trying to get the negative number of a certain one, put the - operator before it.
EDIT: To check whether a bit is 0 or 1, you have to use the bitwise AND.
In two-complement arithmetic to get a reverse number (for example for value 16 to get value -16) you need reverse each bit and add 1.
In your example, to get -16 from 16 that is represented as
00000000000000000000000000010000
you need reverse each bit. You will get
11111111111111111111111111101111
Now you must add 1 and you will get
11111111111111111111111111110000
As you can see if you add these two values, you will get 0. It proves that you did all correctly.

add and remove last bit

I am trying to determine the next and previous even number with bitwise operations.
So for example for the next function:
x nextEven(x)
1 2
2 2
3 4
4 4
and for the previous:
x previousEven(x)
1 0
2 2
3 2
4 4
I had the idea for the nextEven function something like: value = ((value+1)>>1)<<1;
And for the previousEven function something like: value = ((value)>>1)<<1
is there a better approach?, without comparing and seeing if the values are even or odd.
Thank you.
Doing a right shift followed by a left shift to clear the LSB isn't very efficient.
I'd use something like:
previous: value &= ~1;
next: value = (value +1) & ~1;
The ~1 can (and normally will) be pre-computed at compile time, so the previous will end up as a single bit-wise operation at run-time. the next will probably end up as two operations (increment, and), but should still be quite fast.
About the best you can hope for from the shifts is that the compiler will recognize that you're just clearly the LSB, and optimize it to about what you'd expect this to produce anyway.
you could do something like this
for previous even
unsigned prevev(unsigned x)
{
return x-(x%2);//bitwise counterpart x-(x&1);
}
for next even
unsigned nxtev(unsigned x)
{
return (x%2)+x; //bitwise counterpart x+(x&1);
}
Say you're using unsigned ints, previous even (matching your values - we could argue about whether previous even of 2 should be 0 etc) is simply x & ~1u. Next even is previous even of x + 1.
Tricks like Duff's Device, or swapping two variables with XOR, or working out next and previous even number with bitwise operations seem clever, but they rarely are.
The best thing you can do as a developer is to optimise for readability first and only tackle performance once you've identified a specific bottleneck that is causing real problems.
The best code for getting the previous even number (by your definition where the previous even number of 2 is 2) is simply writing something like:
if ((num % 2) == 1) num--; // num++ for next.
or (slightly more advanced):
num -= num % 2; // += for next.
and letting the insane optimising compilers figure out the best underlying code.
Unless you need to do these operations billions of times per second, readability should always be your prime concern.
Previous even number:
For previous even number I prefer Jerry Coffin's answer
// Get previous even number
unsigned prevEven(unsigned no)
{
return (no & ~1);
}
Next even number:
I try to use only bitwise operator's but still i use one unary minus(-) operator to get next number.
// Get next even number
unsigned nextEven(unsigned no)
{
return (no & 1) ? (-(~no)) : no ;
}
Working of Method nextEven():
If number is even return the same number,
if no is even it's LSB is 0 otherwise 1
Get LSB of number => number & 1
If number is odd return the number + 1,
Add 1 to number => -(~number)
unsigned int previous(unsigned int x)
{
return x & 0xfffffffe;
}
unsigned int next(unsigned int x)
{
return previous(x + 2);
}

Counting number of bits: How does this line work ? n=n&(n-1); [duplicate]

This question already has answers here:
n & (n-1) what does this expression do? [duplicate]
(4 answers)
Closed 6 years ago.
I need some explanation how this specific line works.
I know that this function counts the number of 1's bits, but how exactly this line clears the rightmost 1 bit?
int f(int n) {
int c;
for (c = 0; n != 0; ++c)
n = n & (n - 1);
return c;
}
Can some explain it to me briefly or give some "proof"?
Any unsigned integer 'n' will have the following last k digits: One followed by (k-1) zeroes: 100...0
Note that k can be 1 in which case there are no zeroes.
(n - 1) will end in this format: Zero followed by (k-1) 1's: 011...1
n & (n-1) will therefore end in 'k' zeroes: 100...0 & 011...1 = 000...0
Hence n & (n - 1) will eliminate the rightmost '1'. Each iteration of this will basically remove the rightmost '1' digit and hence you can count the number of 1's.
I've been brushing up on bit manipulation and came across this. It may not be useful to the original poster now (3 years later), but I am going to answer anyway to improve the quality for other viewers.
What does it mean for n & (n-1) to equal zero?
We should make sure we know that since that is the only way to break the loop (n != 0).
Let's say n=8. The bit representation for that would be 00001000. The bit representation for n-1 (or 7) would be 00000111. The & operator returns the bits set in both arguments. Since 00001000 and 00000111 do not have any similar bits set, the result would be 00000000 (or zero).
You may have caught on that the number 8 wasn't randomly chosen. It was an example where n is power of 2. All powers of 2 (2,4,8,16,etc) will have the same result.
What happens when you pass something that is not an exponent of 2? For example, when n=6, the bit representation is 00000110 and n-1=5 or 00000101.The & is applied to these 2 arguments and they only have one single bit in common which is 4. Now, n=4 which is not zero so we increment c and try the same process with n=4. As we've seen above, 4 is an exponent of 2 so it will break the loop in the next comparison. It is cutting off the rightmost bit until n is equal to a power of 2.
What is c?
It is only incrementing by one every loop and starts at 0. c is the number of bits cut off before the number equals a power of 2.

Check if integer is multiple of 8

Hi i'm new to c++ so i'm not sure if this is a really silly question. Basically i'm using a c++ custom action project to interact with my MSI installer. I get a property that my user will have entered, it is an integer. I need to ensure that this is a multiple of 8 and i'm not sure how to go about this. Obviously if it can be divided by 8 it is a multiple but I am not sure how to capture if there is a remainder. Any help would be appreciated or even point me in the right direction. Thanks
Use the "modulo" operator, which gives the remainder from division:
if (n % 8 == 0) {
// n is a multiple of 8
}
Use the "modulo" or "integer remainder operator" %:
int a = ....;
if (a % 8 == 0 ) {
// a is amultiple of 8
}
use operator %
if ( num % 8 == 0 )
{
// num is multple of 8
}
Checking only the last 3 digits of a number does the job.
Even if you are given a huge number in the form of a string where the % operating is not useful you can check if only the last 3 digits are divisible by 8 then the whole number is divisible by 8.
For unsigned integers the three least significant bits are always zero for a multiple of 8, so a bitwise & on these bits should be false. For signed (twos complement) this is only true if the integer is positive, so beware if your input is being stored as signed or not (do you want to accept negative numbers as input). Also note the three least significant bits are zero for zero itself, so think if you want your check to be true when someone inputs zero. From your question it doesn't seem like your code has to be optimized so just use modulo.
I saw someone was using bit operation
bool f( int x){
return !(x & 7);
}
It was said this approach has some problem, but I am not quite sure.