How to interpret n & (n - 1) [duplicate] - c++

I'm looking at some code which should be trivial -- but my math is failing me miserably here.
Here's a condition that checks if a number if a power of 2 using the following:
if((num != 1) && (num & (num - 1))) { /* make num pow of 2 */ }
My question is, how does using a bitwise AND between num and num - 1 determine if a number is a power of 2?

Any power of 2 minus 1 is all ones: (2 N - 1 = 111....b)
2 = 2^1. 2-1 = 1 (1b)
4 = 2^2. 4-1 = 3 (11b)
8 = 2^3. 8-1 = 7 (111b)
Take 8 for example. 1000 & 0111 = 0000
So that expression tests if a number is NOT a power of 2.

Well, the first case will check for 20 == 1.
For the other cases the num & (num - 1) comes into play:
That's saying if you take any number, and mask off the bits from one lower, you'll get one of two cases:
if the number is a power of two already, then one less will result in a binary number that only has the lower-order bits set. Using & there will do nothing.
Example with 8: 0100 & (0100 - 1) --> (0100 & 0011) --> 0000
if the number is not a power of two already, then one less will not touch the highest bit, so the result will be at least the largest power of two less than num.
Example with 3: 0011 & (0011 - 1) --> (0011 & 0010) --> 0010
Example with 13: 1101 & (1101 - 1) --> (1101 & 1100) --> 1100
So the actual expression finds everything that isn't a power of two, including 20.

Well,
if you have X = 1000 then x-1 = 0111. And 1000 && 0111 is 0000.
Each number X that is a power of 2 has an x-1 that has ones on the position x has zeroes. And a bitwise and of 0 and 1 is always 0.
If the number x is not a power of two, for example 0110. The x-1 is 0101 and the and gives 0100.
For all combinbations within 0000 - 1111 this leads to
X X-1 X && X-1
0000 1111 0000
0001 0000 0000
0010 0001 0000
0011 0010 0010
0100 0011 0000
0101 0100 0100
0110 0101 0100
0111 0110 0110
1000 0111 0000
1001 1000 1000
1010 1001 1000
1011 1010 1010
1100 1011 1000
1101 1100 1100
1110 1101 1100
1111 1110 1110
And there is no need for a separate check for 1.

I prefer this approach that relies on two's complement:
bool checkPowTwo(int x){
return (x & -x) == x;
}

Explained here nicely
Also the expression given considers 0 to be a power of 2. To fix that use
!(x & (x - 1)) && x; instead.

It determines whether integer is power of 2 or not. If (x & (x-1)) is zero then the number is power of 2.
For example,
let x be 8 (1000 in binary); then x-1 = 7 (0111).
if 1000
& 0111
---------------
0000
C program to demonstrate:
#include <stdio.h>
void main()
{
int a = 8;
if ((a&(a-1))==0)
{
printf("the bit is power of 2 \n");
}
else
{
printf("the bit is not power of 2\n");
}
}
This outputs the bit is power of 2.
#include <stdio.h>
void main()
{
int a = 7;
if ((a&(a-1))==0)
{
printf("the bit is power of 2 \n");
}
else
{
printf("the bit is not power of 2\n");
}
}
This outputs the bit is not power of 2.

Suppose n is the given number,
if n is power of 2 (n && !(n & (n-1)) will return 1 else return 0

When you decrement a positive integer by 1:
if it is zero, you get -1.
if its least significant bit is 1, this bit is set to 0, the other bits are unchanged.
otherwise, all the low order 0 bits are set to 1 and the lowest 1 bit if set to 0, the other bits are unchanged.
Case 1: x & (x - 1) is 0, yet x is not a power of 2, trivial counter example.
Cases 2 and 3: if x and x-1 have no bits in common, it means the other bits in both of the above cases are all zero, hence the number has a single 1 bit, hence it is a power of 2.
If x is negative, this test does not work for two's complement representation of signed integers as either decrementing overflows or x and x-1 have at least the sign bit in common, which means x & (x-1) is not zero.
To test for a power of 2 the code should be:
int is_power_of_2(unsigned x) {
return x && !(x & (x - 1));
}

#include <stdio.h>
void powerof2(int a);
int a;
int main()
{
while(1)
{
printf("Enter any no. and Check whether no is power of 2 or no \n");
scanf("%d",&a);
powerof2(a);
}
}
void powerof2(int a)
{
int count = 0;
int b=0;
while(a)
{
b=a%2;
a=a/2;
if(b == 1)
{ count++; }
}
if(count == 1)
{
printf("power of 2\n");
}
else
printf("not power of 2\n");
}

Following program in C will find out if the number is power of 2 and also find which power of 2, the number is.
#include<stdio.h>
void main(void)
{
unsigned int a;
unsigned int count=0
unsigned int check=1;
unsigned int position=0;
unsigned int temp;
//get value of a
for(i=0;i<sizeof(int)*8;i++)//no of bits depend on size of integer on that machine
{
temp = a&(check << i);
if(temp)
{
position = i;
count++;
}
}
if(count == 1)
{
printf("%d is 2 to the power of %d",a,position);
}
else
{
printf("Not a power of 2");
}
}
There are other ways to do this:-
if a number is a power of 2, only 1 bit will be set in the binary format
for example 8 is equivalent to 0x1000, substracting 1 from this, we get 0x0111.
End operation with the original number(0x1000) gives 0.
if that is the case, the number is a power of 2
void IsPowerof2(int i)
{
if(!((i-1)&1))
{
printf("%d" is a power of 2, i);
}
}
another way can be like this:-
If we take complement of a number which is a power of 2,
for example complement of 8 i.e 0x1000 , we get 0x0111 and add 1 to it, we get
the same number, if that is the case, that number is a power of 2
void IsPowerof2(int i)
{
if(((~1+1)&i) == 1)
{
printf("%d" is a power of 2,i):
}
}

Related

Unitary number for “&” bitwise operator in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a question, I would appreciate it if you helped me to understand it. Imagin I define the following number
c= 0x3FFFFFFF
and a = an arbitrary integer number=Q. My question is, why a &= c always is equal to "Q" and it does not change? for example, if I consider a=10 then the result of a &= c is 10 if a=256 the result of a &= c is 256. Could you please explain why? Thanks a lot.
Both a and c are integer types and are composed of 32 bits in a computer. The first digit of an integer in a computer is the sign bit.The first digit of a positive number is 0, and the first digit of a negative number is 1. 0x3FFFFFFF is a special value. The first two digits of this number are 0, and the other digits are all 1. 1 & 1 = 1, 1 & 0 = 0. So when the number a a is positive and less than c, a & 0x3FFFFFFF is still a itself
a &= c is the same as a = a & c, which calculates the binary and of a and b and then assign that value to a again - just in case you've mistaken what that operator does.
Now a contains almost only 1's. Then just think what each bit becomes: 1 & x will always be x. Since you try with such low numbers only, none of them will change.
Try with c=0xffffffff and you will get a different result.
You have not tested a &= c; with all possible values of a and are incorrect to assert it does not change the value of a in all cases.
a &= c; sets a to a value in which each bit is set if the two bits in the same position in a and in c are both set. If the two bits are not both set, 5he bit in the result is clear.
In 0x3FFFFFFF, the 30 least significant bits are set. When this is used in a &= c; with any number in which higher bits are set, such as 0xC0000000, the higher bits will be cleared.
If you know about bitwise & ("and") operation and how it works, then there should be no question about this. Say, you have two numbers a and b. Each of them are n-bits long. Look,
a => a_(n-1) a_(n-2) a_(n-3) ... a_i ... a_2 a_1 a_0
b => b_(n-1) b_(n-2) b_(n-3) ... b_i ... b_2 b_1 b_0
Where a_0 and b_0 are the least significant bits and a_(n-1) and b_(n-1) are the most significant bits of a and b respectively.
Now, take a look at the & operation on two single binary bits.
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
So, the result of the & operation is 1 only when all bits are 1. If at least one bit is 0, then the result is 0.
Now, for n-bits long number,
a & b = (a_i & b_i); where `i` is from 0 to `n-1`
For example, if a and b both are 4 bits long numbers and a = 5, b = 12, then
a = 5 => a = 0101
b = 12 => b = 1100
if c = (a & b), c_i = (a_i & b_i) for i=0..3, here all numbers are 4 bits(0..3)
now, c = c_3 c_2 c_1 c_0
so c_3 = a_3 & b_3
c_2 = a_2 & b_2
c_1 = a_1 & b_1
c_0 = a_0 & b_0
a 0 1 0 1
b 1 1 0 0
-------------
c 0 1 0 0 (that means c = 4)
therefore, c = a & b = 5 & 12 = 4
Now, what would happen, if all of the bits in one number are 1s?
Let's see.
0 & 1 = 0
1 & 1 = 1
so if any bit is fixed and it 1, then the result is the same as the other bit.
if a = 5 (0101) and b = 15 (1111), then
a 0 1 0 1 (5)
b 1 1 1 1 (15)
------------------
c 0 1 0 1 (5, which is equal to a=5)
So, if any of the numbers has all bits are 1s, then the & result is the same as the other number. Actually, for a=any value of 4-bits long number, you will get the result as a, since b is 4-bits long and all 4 bits are 1s.
Now another issue would happen, when a > 15 means a exceeds 4-bits
For the above example, expand the bit size to 1 and change the value of a is 25.
a = 25 (11001) and b = 15 (01111). Still, b is the same as before except the size. So the Most Significant Bit (MSB) is 0. Now,
a 1 1 0 0 1 (25)
b 0 1 1 1 1 (15)
----------------------
c 0 1 0 0 1 (9, not equal to a=25)
So, it is clear that we have to keep every single bit to 1 if we want to get the other number as the result of the & operation.
Now it is time to analyze the scenario you posted.
Here, a &= c is the same as a = a & c.
We assumed that you are using 32-bit integer variables.
You set c = 0x3FFFFFFF means c = (2^30) - 1 or c = 1073741823
a = 0000 0000 0000 0000 0000 0000 0000 1010 (10)
& c = 0011 1111 1111 1111 1111 1111 1111 1111 (1073741823)
----------------------------------------------------------------
a = 0000 0000 0000 0000 0000 0000 0000 1010 (10, which is equal to a=10)
and
a = 0000 0000 0000 0000 0000 0001 0000 0000 (256)
& c = 0011 1111 1111 1111 1111 1111 1111 1111 (1073741823)
----------------------------------------------------------------
a = 0000 0000 0000 0000 0000 0001 0000 0000 (256, which is equal to a=256)
but, if a > c, say a=0x40000000 (1073741824, c+1 in base 10), then
a = 0100 0000 0000 0000 0000 0001 0000 0000 (1073741824)
& c = 0011 1111 1111 1111 1111 1111 1111 1111 (1073741823)
----------------------------------------------------------------
a = 0000 0000 0000 0000 0000 0000 0000 0000 (0, which is not equal to a=1073741823)
So, your assumption ( the value of a after executing statement a &= c is the same as previous a) is true only if a <= c

What do "Non-Power-Of-Two Textures" mean?

What do "Non-Power-Of-Two Textures" mean? I read this tutorial and I meet some binaries operations("<<", ">>", "^", "~"), but I don't understand what they are doing.
For example following code:
GLuint LTexture::powerOfTwo(GLuint num)
{
if (num != 0)
{
num--;
num |= (num >> 1); //Or first 2 bits
num |= (num >> 2); //Or next 2 bits
num |= (num >> 4); //Or next 4 bits
num |= (num >> 8); //Or next 8 bits
num |= (num >> 16); //Or next 16 bits
num++;
}
return num;
}
I very want to understand this operations. As well, I read this. Very short article. I want to see examples of using, but I not found. I did the test:
int a = 5;
a <<= 1; //a = 10
a = 5;
a <<= 2; //a = 20
a = 5;
a <<= 3; //a = 40
Okay, this like multiply on two, but
int a = 5;
a >>= 1; // a = 2 Whaat??
In C++, the <<= is the "left binary shift" assignment operator; the operand on the left is treated as a binary number, the bits are moved to the left, and zero bits are inserted on the right.
The >>= is the right binary shift; bits are moved to the right and "fall off" the right end, so it's like a division by 2 (for each bit) but with truncation. For negative signed integers, by the way, additional 1 bits are shifted in at the left end ("arithmetic right shift"), which may be surprising; for positive signed integers, or unsigned integers, 0 bits are shifted in at the left ("logical right shift").
"Powers of two" are the numbers created by successive doublings of 1: 2, 4, 8, 16, 32… Most graphics hardware prefers to work with texture maps which are powers of two in size.
As said in http://lazyfoo.net/tutorials/OpenGL/08_non_power_of_2_textures/index.php
powerOfTwo will take the argument and find nearest number that is power of two.
GLuint powerOfTwo( GLuint num );
/*
Pre Condition:
-None
Post Condition:
-Returns nearest power of two integer that is greater
Side Effects:
-None
*/
Let's test:
num=60 (decimal) and its binary is 111100
num--; .. 59 111011
num |= (num >> 1); //Or first 2 bits 011101 | 111011 = 111111
num |= (num >> 2); //Or next 2 bits 001111 | 111111 = 111111
num |= (num >> 4); //Or next 4 bits 000011 | 111111 = 111111
num |= (num >> 8); //Or next 8 bits 000000 | 111111 = 111111
num |= (num >> 16); //Or next 16 bits 000000 | 111111 = 111111
num++; ..63+1 = 64
output 64.
For num=5: num-1 =4 (binary 0100), after all num |= (num >> N) it will be 0111 or 7 decimal). Then num+1 is equal to 8.
As you should know the data in our computers is represented in the binary system, in which digits are either a 1 or a 0.
So for example number 10 decimal = 1010 binary. (1*2^3 + 0*2^2 + 1*2^1 + 0*2^0).
Let's go to the operations now.
Binary | OR means that wherever you have at least one 1 the output will be 1.
1010
| 0100
------
1110
~ NOT means negation i.e. all 0s become 1s and all 1s become 0s.
~ 1010
------
0101
^ XOR means you turn a pair of 1 and 0 into a 1. All other combinations leave a 0 as output.
1010
^ 0110
------
1100
Bit shift.
N >> x means we "slide" our number N, x bits to the right.
1010 >> 1 = 0101(0) // zero in the brackets is dropped,
since it goes out of the representation = 0101
1001 >> 1 = 0100(1) // (1) is dropped = 0100
<< behaves the same way, just the opposite direction.
1000 << 1 = 0001
Since in binary system numbers are represented as powers of 2, shifting a bit one or the other direction will result in multiplying or dividing by 2.
Let num = 36. First subtract 1, giving 35. In binary, this is 100011.
Right shift by 1 position gives 10001 (the rightmost digit disappears). Bitwise Or'ed with num gives:
100011
10001
-------
110011
Note that this ensures two 1's on the left.
Now right shift by 2 positions, giving 1100. Bitwise Or:
110011
1100
-------
111111
This ensures four 1's on the left.
And so on, until the value is completely filled with 1's from the leftmost.
Add 1 and you get 1000000, a power of 2.
This procedure always generates a power of two, and you can check that it is just above the initial value of num.

How does condition statement work with bit-wise operators?

I tried to understand how if condition work with bitwise operators.
A way to check if a number is even or odd can be done by:
#include <iostream>
#include <string>
using namespace std;
string test()
{
int i = 8; //a number
if(i & 1)
return "odd";
else
return "even";
}
int main ()
{
cout << test();
return 0;
}
The Part I don't understand is how the if condition work. In this case if i = 8 then the in If statement it is doing 1000 & 1 which should gives back 1000 which equal 8.
If i = 7, then in if statement it should be doing 111 & 1 which gives back 111 which equal 7
Why is it the case that if(8) will return "even" and if(7) return "odd"? I guess I want to understand what the if statement is checking to be True and what to be False when dealing with bit-wise operators.
Just A thought when I wrote this question down is it because it's actually doing
for 8: 1000 & 0001 which gives 0
for 7: 0111 & 0001 which gives 1?
Yes, you are right in the last part. Binary & and | are performed bit by bit. Since
1 & 1 == 1
1 & 0 == 0
0 & 1 == 0
0 & 0 == 0
we can see that:
8 & 1 == 1000 & 0001 == 0000
and
7 & 1 == 0111 & 0001 == 0001
Your test function does correctly compute whether a number is even or odd though, because a & 1 tests whether there is a 1 in the 1s place, which there only is for odd numbers.
Actually, in C, C++ and other major programming languages the & operator do AND operations in each bit for integral types. The nth bit in a bitwise AND is equal to 1 if and only if the nth bit of both operands are equal to 1.
For example:
8 & 1 =
1000 - 8
0001 - 1
----
0000 - 0
7 & 1 =
0111 - 7
0001 - 1
----
0001 - 1
7 & 5 =
0111 - 7
0101 - 5
----
0101 - 5
For this reason doing a bitwise AND between an even number and 1 will always be equal 0 because only odd numbers have their least significant bit equal to 1.
if(x) in C++ converts x to boolean. An integer is considered true iff it is nonzero.
Thus, all if(i & 1) is doing is checking to see if the least-significant bit is set in i. If it is set, i&1 will be nonzero; if it is not set, i&1 will be zero.
The least significant bit is set in an integer iff that integer is odd, so thus i&1 is nonzero iff i is odd.
What you say the code is doing is actually how bit-wise operators are supposed to work. In your example of (8 & 1):
1000 & 0001 = 0000
because in the first value, the last bit is set to 0, while in the second value, the last bit is set to 1. 0 & 1 = 0.
0111 & 0001 = 0001
In both values, the last bit is set to 1, so the result is 1 since 1 & 1 = 1.
The expression i & 1, where i is an int, has type int. Its value is 1 or 0, depending on the value of the low bit of i. In the statement if(i & 1), the result of that expression is converted to bool, following the usual rule for integer types: 0 becomes false and non-zero becomes true.

How does this implementation of bitset::count() work?

Here's the implementation of std::bitset::count with MSVC 2010:
size_t count() const
{ // count number of set bits
static char _Bitsperhex[] = "\0\1\1\2\1\2\2\3\1\2\2\3\2\3\3\4";
size_t _Val = 0;
for (int _Wpos = _Words; 0 <= _Wpos; --_Wpos)
for (_Ty _Wordval = _Array[_Wpos]; _Wordval != 0; _Wordval >>= 4)
_Val += _Bitsperhex[_Wordval & 0xF];
return (_Val);
}
Can someone explain to me how this is working? what's the trick with _Bitsperhex?
_Bitsperhex contains the number of set bits in a hexadecimal digit, indexed by the digit.
digit: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
value: 0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4
index: 0 1 2 3 4 5 6 7 8 9 A B C D E F
The function retrieves one digit at a time from the value it's working with by ANDing with 0xF (binary 1111), looks up the number of set bits in that digit, and sums them.
_Bitsperhex is a 16 element integer array that maps a number in [0..15] range to the number of 1 bits in the binary representation of that number. For example, _Bitsperhex[3] is equal to 2, which is the number of 1 bits in the binary representation of 3.
The rest is easy: each multi-bit word in internal array _Array is interpreted as a sequence of 4-bit values. Each 4-bit value is fed through the above _Bitsperhex table to count the bits.
It is a slightly different implementation of the lookup table-based method described here: http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetTable. At the link they use a table of 256 elements and split 32-bit words into four 8-bit values.

Can I set a sequence of bits without unsetting the previous values?

I've got a sequence of bits, say
0110 [1011] 1111
Let's say I want to set that myddle nybble to 0111 as the new value.
Using a positional masking approach with AND or OR, I seem to have no choice but to first unset the original value to 0000, because if I trying ANDing or ORing against that original value of 1011, I'm not going to come out with the desired result of 0111.
Is there another logical operator I should be using to get the desired effect? Or am I locked into 2 operations every time?
The result after kindly assistance was:
inline void foo(Clazz* parent, const Uint8& material, const bool& x, const bool& y, const bool& z)
{
Uint8 offset = x | (y << 1) | (z << 2); //(0-7)
Uint64 positionMask = 255 << offset * 8; //255 = length of each entry (8 bits), 8 = number of bits per material entry
Uint64 value = material << offset * 8;
parent->childType &= ~positionMask; //flip bits to clear given range.
parent->childType |= value;
}
...I'm sure this will see further improvement, but this is the (semi-)readable version.
If you happen to already know the current values of the bits, you can XOR:
0110 1011 1111
^ 0000 1100 0000
= 0110 0111 1111
(where the 1100 needs to be computed first as the XOR between the current bits and the desired bits).
This is, of course, still 2 operations. The difference is that you could precompute the first XOR in certain circumstances.
Other than this special case, there is no other way. You fundamentally need to represent 3 states: set to 1, set to 0, don't change. You can't do this with a single binary operand.
You may want to use bit fields (and perhaps unions if you want to be able to access your structure as a set of bit fields and as an int at the same time) , something along the lines of:
struct foo
{
unsigned int o1:4;
unsigned int o2:4;
unsigned int o3:4;
};
foo bar;
bar.o2 = 0b0111;
Not sure if it translates into more efficient machine code than your clear/set...
Well, there's an assembly instruction in MMIX for this:
SETL $1, 0x06BF ; 0110 1011 1111
SETL $2, 0x0070 ; 0000 0111 0000
SETL rM, 0x00F0 ; set mask register
MUX $1,$2,$1 ; result is 0110 0111 1111
But in C++ here's what you're probably thinking of as 'unsetting the previous value'.
int S = 0x6BF; // starting value: 0110 1011 1111
int M = 0x0F0; // value mask: 0000 1111 0000
int V = 0x070; // value: 0000 0111 0000
int N = (S&~M) | V; // new value: 0110 0111 1111
But since the intermediate result 0110 0000 1111 from (S&~M) is never stored in a variable anywhere I wouldn't really call it 'unsetting' anything. It's just a bitwise boolean expression. Any boolean expression with the same truth table will work. Here's another one:
N = ((S^V) & M) ^ A; // corresponds to Oli Charlesworth's answer
The related truth tables:
S M V (S& ~M) | V ((S^V) & M) ^ S
0 0 0 0 1 0 0 0 0
* 0 0 1 0 1 1 1 0 0
0 1 0 0 0 0 0 0 0
0 1 1 0 0 1 1 1 1
1 0 0 1 1 1 1 0 1
* 1 0 1 1 1 1 0 0 1
1 1 0 0 0 0 1 1 0
1 1 1 0 0 1 0 0 1
^ ^
|____________________|
The rows marked with '*' don't matter because they won't occur (a bit in V will never be set when the corresponding mask bit is not set). Except for those rows, the truth tables for the expressions are the same.