Truncate binary number [duplicate] - c++

This question already has answers here:
Getting the Leftmost Bit
(9 answers)
Closed 9 years ago.
I would like to truncate every digit after the first non zero digit in the binary representation of an integer. I also need this to be as simple as possible (no function or multiple lines of code).
In example:
// in c++
int int1=7,int2=12,int3=34; //needs to work for any number
using some sort of operator (maybe bitwise combination?), I need these to give the following values
int1 -> 4
int2 -> 8
int3 -> 32
Truncating in binary was the only thing I could think of, so I am open to any ideas.
Thanks!

A pretty neat trick can be used for that:
if ((v & (v - 1)) == 0) {
return v;
}
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
v >>= 1;
return v;
The idea is to "OR in" all ones below the top one after decrementing the value, and then increment the value back at the end. I added a shift right at the end to the standard trick, because the original code was designed to find the smallest 2^n greater than or equal to the given value.
EDIT: I also added a special case for 2^N, which is another trick from the same list.
Here is a demo on ideone.

This function is from the book Hacker's Delight.
// greatest power of 2 less than or equal to n (floor pow2)
uint32_t flp2(uint32_t n)
{
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n - (n >> 1);
}
And I might as well post the related clp2 function:
// least power of 2 greater than or equal to n (ceiling pow2)
uint32_t clp2(uint32_t n)
{
n -= 1;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}

Related

Maximum XOR With an Element From Array | Leetcode

I was practicing on Leetcode and came across this problem.
Problem statement (link):
You are given an array nums consisting of non-negative integers.
You are also given a queries array, where queries[i] = [xi, mi].
The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi.
In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi.
If all elements in nums are larger than mi, then the answer is -1.
Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.
Constraints:
1 <= nums.length, queries.length <= 10^5
queries[i].length == 2
0 <= nums[j], xi, mi <= 10^9
I solved this question using the trie approach and went to discuss section to see other's solutions. There, I came across this solution (link):
class Solution {
public:
vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {
const int n = nums.size(), q = queries.size();
vector<int> ans(q, -1);
sort(nums.begin(), nums.end());
for (int i = 0; i < q; i++) {
const int x = queries[i][0], m = queries[i][1];
if (m < nums[0]) continue;
int end = upper_bound(nums.begin(), nums.end(), m) - nums.begin();
int start = 0;
int k = 0, cur = 0;
for (int bit = 31; bit >= 0; bit--) {
if (x & (1 << bit)) { // hope A[i] this bit == 0
if (!(nums[start] & (1 << bit))) {
k |= 1 << bit;
end = lower_bound(nums.begin() + start, nums.begin() + end, cur | (1 << bit)) - nums.begin();
} else {
cur |= 1 << bit;
}
} else { // hope: A[i] this bit == 1
if (start <= end - 1 && (nums[end - 1] & (1 << bit))) {
k |= 1 << bit;
cur |= 1 << bit;
start = lower_bound(nums.begin() + start, nums.begin() + end, cur) - nums.begin();
}
}
}
ans[i] = k;
}
return ans;
}
};
Unfortunately, I'm not able to understand this solution. I would appreciate it if someone can give a proper explanation for this solution (mainly while looping through bits).
There are some issues with this implementation. start and end should remain iterators, they could be used directly without adding/subtracting nums.begin() all the time. We're talking about non-negative integers, so provided they fit into normal int first bit is 0 anyway, so we should start with int bit = 30 to skip one needless iteration. For integers right as for iterators as well, start <= end - 1 is better compared as start < end. The code consists of one single function, there's absolutely no need for a class then, so one should prefer a namespace. Applying these changes, the code would look like this:
namespace Solution
{
// as EXACTLY two values, std::pair is more appropriate
// we are not modifying queries, so should be accepted as const
std::vector<int> maximizeXor
(
std::vector<int>& nums, std::vector<std::pair<int, int>>const& queries
)
{
const int q = queries.size();
std::vector<int> ans(q, -1);
sort(nums.begin(), nums.end());
// remove duplicates:
// -> less numbers to iterate over
nums.erase(unique(nums.begin(), nums.end()), nums.end());
for (int i = 0; i < q; ++i)
{
int const x = queries[i].first, m = queries[i].second;
// we have a sorted array, remember?
// if first value is larger than the query maximum, then there are no
// corresponding numbers – and as the vector is initialised to -1
// anyway, the appropriate value is there already so we can simply skip
if (m < nums[0])
{
continue;
}
// using iterators pointing at the appropriate indices
auto end = upper_bound(nums.begin(), nums.end(), m);
auto start = nums.begin();
int /*k = 0,*/ cur = 0;
// intention is to check each bit of x
// modifying the loop!
//for (int bit = 30; bit >= 0; bit--)
int const MaxBit = 1 << sizeof(int) * CHAR_BIT - 2;
for (int bit = MaxBit; start != prev(end); bit >>= 1)
{
// OK; fixing an issue and adding some tricks to handle the loop
// a bit cleverer...
// sizeof(int) * CHAR_BIT: int is NOT guaranteed to have exactly
// 32 bits! if you want to be on the safe side, either calculate
// as above or use int32_t instead
// changed abort condition:
// I modified the algorithm slightly such that we can break early
// unique'ing the vector allows us to drop the original
// condition bit >= 0 entirely, this will be explained later
// I store the bit-MASK in bit now, now we do not have to
// calculate it again and again (1 << bit)
if (x & bit)
{
// so x has a 1-bit at bit index 'bit'
// in the range yet to be considered we have two groups of
// numbers:
// 1. those having a 0-bit at bit-index 'bit'
// 2. those having a 1-bit
// if we compare single bits, we get:
// x = *1***
// num = *0*** XOR: *1***
// num = *1*** XOR: *0***
// IF now there are numbers with a zero bit at all, then one
// of these will produce the maximum, whereas those with a
// 1-bit cannot asnumbers are sorted, we can just check very
// first value of the range:
// any number having a 1-bit at the same bit index will produce
// a zero-bit – thus these numbers CANNOT produce the maximum
if (!(*start & bit))
{
// bits differ, remember?
// thus the XOR will have a one-bit we store right now
// actually, we do NOT need that, we can handle that cleverer
//k |= 1 << bit;
// instead, I handle this with the NEW loop condition
// fine – there ARE numbers with zero-bits, so remove all
// numbers with 1-bit from range; as they all are at the end
// of, we simply move this one towards front:
end = lower_bound(start, end, cur | bit);
// cur contains those bits of the number producing the
// maximum that have been evaluated so far, it is a
// lower bound for – we do NOT modify it, but we can
// calculate a new upper bound from!
}
else
{
// well, there is no such number with a 0-bit
// we cannot move end or start position
cur |= bit;
}
}
else
{
// analogously:
// x = *0***
// num = *0*** XOR: *0***
// num = *1*** XOR: *1***
// so all members having a 1-bit are of interest – IF there
// are – and we can skip those numbers with 0-bit at the
// beginning
// if there are, then they are at the very end
// 'end' iterator points to one past, so we need predecessor
if (/*start < end &&*/ *prev(end) & bit)
{
// first condition is handled in the loop now
// as above: we can handle that cleverer
//k |= 1 << bit;
// now current mask NEEDS the one-bit
cur |= bit;
start = lower_bound(start, end, cur);
}
}
// with unchanged loop it was not possible to break early as k still
// needed to be calculated
//ans[i] = k;
// with or without early break, we can always:
ans[i] = *start ^ x;
// with every iteration, we extend the bit mask 'cur' the numbers
// have to match with by one bit (either the 0 gets confirmed
// or replaced by a 1).
// After 31 iterations (sign bit is ignored as we only have
// positive integers), *all* bits are defined (if we had omitted
// the early breaks we could have calculated
// ans[i] = cur ^ x; as well...).
// so all numbers that yet might have remained in the valid range
// must match this pattern, i. e. be equal. However as unique-ing,
// there is exactly one single value left...
}
}
return ans;
}
} // namespace Solution
Be aware that std::lower_bound has (random access iterators provided, as is with std::vector) a complexity of O(log(n)), so executing one single query has O(log(n)) with n being the amount of numbers. Adding the overhead of sorting and querying m times, we get a total complexity of O(n*log(n) + m*log(n)) = O((n+m)*log(n)) compared to 'naive' iteration with complexity of O(m*n). If m is of similar magnitude as n or larger we have a complexity advantage (already in original variant, my adjustments just trim the constants a bit, but do not change complexity).

Count total set-bits from 1 to n

I tried to solve this using loops. Can anyone tell me where I went wrong and what will be the output of it? I have tried using count set-bits concept for a given number.
#include <bits/stdc++.h>
using namespace std;
int main()
{
int res=0;
int n;
cout<<"Enter the value of n";
cin>>n;
for(int i=1;i<=n;i++)
{
while(i>0)
{
if((i & 1)==1)//checks whether the last bit is 1
{
res++; //res will count the set bits
}
i=i>>1;
}
}
cout<<res;
}
General rule of thumb: Avoid modifying loop counter variables while iterating.
You're trying to loop i from 1 to n, but you modify i inside the loop and mess up successive iterations of the for loop. I advise making a copy of i and only modifying the copy.
I will show some additional methods, how this can be done. There are some interesting approaches. Especially the last methods, which are taken from the book Hackers Delight. Unfortunately I cannot cite several pages from the book for the explanation. Please check the book.
But we will start with the standard "masking" approach. Easy to understand.
Next we will use a well known method, which is shown here on SO many times. It is about how to delete the right most set bit.
Method 3 is the "modern C++" solution using a std::bitset
Method 4 and 5 use a Divide and Conquer approach. They will produce some optimzed code for certain microcontrollers.
Please see the following example:
#include <iostream>
#include <bitset>
int main() {
std::cout << "Enter an unsigned integer number: ";
// Read number and check, if that worked
if (unsigned int number{}; std::cin >> number) {
// Method 1. Standard approach
{
unsigned int n{ number };
unsigned int mask{ 1 };
size_t count{};
for (size_t i{}; i < sizeof(n) * 8; ++i) {
if (n & mask) ++count;
mask <<= 1;
}
std::cout << "\nMethod 1. Standard approach with masking. Set bits: " << count << '\n';
}
// Method 2. Improved version. Alwyas delete last set bit
{
unsigned int n{ number };
size_t count{};
while (n != 0) {
++count;
// Deleting the rightmost set bit
n = n & (n - 1);
}
std::cout << "\nMethod 2. Improved version. Alwyas delete last set bit. Set bits: " << count << '\n';
}
// Method 3. Using std::bitset
{
unsigned int n{ number };
std::cout << "\nMethod 3. std::bitset. Set bits: " << std::bitset<32>(n).count() << '\n';
}
// Method 4. Loopless optimized Source: Hackers Delight
{
unsigned int n{ number };
n = n - ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
n = (n + (n >> 4)) & 0x0f0f0f0f;
n = n + (n >> 8);
n = n + (n >> 16);
n = n & 0x0000003f;
std::cout << "\nMethod 4. Hackers Delight 1. Set bits: " << n << '\n';
}
// Method 5. Loopless optimized Source: Hackers Delight 5
{
unsigned int x{ number };
unsigned int n = (x >> 1) & 033333333333; // Octal constant
x = x - n;
n = (n >> 1) & 033333333333; // Octal constant
x = x - n;
x = ((x + (x >> 3)) & 030707070707) % 63;
std::cout << "\nMethod 5. Hackers Delight 2. Set bits: " << x << '\n';
}
}
else (std::cerr << "\n\nError: Invalid input\n");
return 0;
}

What n&1 and n>>=1 mean? [duplicate]

This question already has answers here:
What is (x & 1) and (x >>= 1)?
(5 answers)
Closed 2 years ago.
I was doing this exercise : https://www.hackerrank.com/challenges/30-binary-numbers/problem and I found this code, but I didn't understand what the condition with n&1 and n>>=1 do here.
//C++ program to convert a decimal
// number to binary number
#include <iostream>
using namespace std;
int main()
{
int n,count=0,max=0;
cin >> n;
while(n)
{
if (n&1)
count++;
else
count = 0;
if (max < count)
max = count;
n>>=1;
}
cout << max;
return 0;
}
if (n&1)
checks whether n is odd by doing a bitwise and.
n>>=1;
shifts the bits of n to the right by one bit.
The & is a bitwise-AND operator and evaluates the expression in either true or false (when the expression is conditional), it's pretty much similar to x % 2, i.e. this condition:
if (n & 1) {
//...
}
// is equal to
if (n % 2) {
// ...
}
OTOH, n >>= 1 shifts right n by a bit.

Inverting the bits of an even number in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
A girl writes N numbers on the board (odd and even numbers) and then, she modifies only even numbers and inverts its binary representation (from the left to the right ) and replaces each even number. Write a code for the same.
0 <= n <= 10^7
I made a code for this, where my partial code looks like this:
int a[100000];
while ( t != 0 ) // t is the number in which input is taken
{
k = t & 1;
if ( k == 1 )
a[i] = 0; // a is the array in which bits of new number will be stored
else
a[i] = 1;
i++;
t = t >> 1;
}
for ( j = i; j >= 0; j-- )
{
if (a[j] == 1)
{
num = num + pow(2,j)*a[j]; // num is the number to be formed
}
}
cout<<num<<"\n";
But my answer comes out to be wrong for some values, for example for 8, it outputs 7. What is wrong with this? Thanks!
Problem link:
http://www.spoj.com/problems/EC_CONB/
Edit: ( In response to Pete's answer )
while ( t != 0 )
{
k = t & 1;
if ( k == 1 )
a[i] = 0;
else
{
a[i] = 1;
num = num + pow(2,i);
}
i++;
t = t >> 1;
}
cout<<num<<"\n";
}
This still shows the same problem, outputs the value of 8 as 7.
The problem actually wants you to reverse the bits not invert them. So the part where you check if k == 1, and putting 0 instead is not correct, because that inverts the bits.
What you need to do is reverse the ordering of the bits as follows:
1000 (8) -> 0001 (1)
1010 (10) -> 0101 (5)
Sample code based on your code:
while (t != 0)
{
k = t & 1;
// push the output array to the left
num <<= 1;
// add the read bit to the beginning of the output array
num += k;
t = t >> 1;
}
Explanation:
The basic idea is that we read bits from the input number one-by-one, and push them to the beginning of the output number.
Below is a trace of reversing a number (1011) at each iteration:
iterations 0 1 2 3 4
input 1011 101 10 1 0
output 0 1 11 110 1101
You appear to be reading a[i] after incrementing i, so the behaviour is undefined.
Instead of creating an array, accumulate the result in the first loop.
Arrays? Loops? Not necessary.
Reversing the number like that is equivalent to completely reversing the integer and then right-justifying it, like this (not tested)
// reverse from http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
// swap odd and even bits
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);
// swap consecutive pairs
v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);
// swap nibbles ...
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = ( v >> 16 ) | ( v << 16);
// right-justify
v /= v & -v;
v should be an uint32_t.

Print number of 1s in a sequence up to a number, without actually counting 1s [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
An interview question:
Make a program which takes input 'N'(unsigned long) and prints two columns, 1st column prints numbers from 1 to N (in hexadecimal format) and second column prints the number of 1s in the binary representation of the number in the left column. Condition is that this program should not count 1s (so no computations 'per number' to get 1s/ no division operators).
I tried to implement this by leveraging fact that No of 1s in 0x0 to 0xF can be re-used to generate 1s for any number. I am pasting code ( basic one without error checking.) Its giving correct results but I am not happy with space usage. How can I improve on this?
( Also I am not sure if its what interviewer was looking for).
void printRangeFasterWay(){
uint64_t num = ~0x0 ;
cout << " Enter upper number " ;
cin >> num ;
uint8_t arrayCount[] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4} ;
// This array will store information needed to print
uint8_t * newCount = new uint8_t[num] ;
uint64_t mask = 0x0 ;
memcpy(newCount, &arrayCount[0], 0x10) ;
uint64_t lower = 0;
uint64_t upper = 0xF;
uint64_t count = 0 ;
uint32_t zcount= 0 ;
do{
upper = std::min(upper, num) ;
for(count = lower ; count <= upper ; count++){
newCount[count] = (uint32_t)( newCount[count & mask] + newCount[(count & ~mask)>>(4*zcount)]) ;
}
lower += count ;
upper |= (upper<<4) ;
mask = ((mask<<4) | 0xF ) ;
zcount++ ;
}while(count<=num) ;
for(uint64_t xcount=0 ; xcount <= num ; xcount++){
cout << std::hex << " num = " << xcount << std::dec << " number of 1s = " << (uint32_t)newCount[xcount] << endl;
}
}
Edited to add sample run
Enter upper number 18
num = 0 number of 1s = 0
num = 1 number of 1s = 1
num = 2 number of 1s = 1
num = 3 number of 1s = 2
num = 4 number of 1s = 1
num = 5 number of 1s = 2
num = 6 number of 1s = 2
num = 7 number of 1s = 3
num = 8 number of 1s = 1
num = 9 number of 1s = 2
num = a number of 1s = 2
num = b number of 1s = 3
num = c number of 1s = 2
num = d number of 1s = 3
num = e number of 1s = 3
num = f number of 1s = 4
num = 10 number of 1s = 1
num = 11 number of 1s = 2
num = 12 number of 1s = 2
I have a slightly different approach which should solve your memory problem. Its based on the fact that the bitwise operation i & -i gives you the smallest power of two in the number i. For example, for i = 5, i & -i = 1, for i = 6, i & -i = 2. Now, for code:
void countBits(unsigned N) {
for (int i = 0;i < N; i ++)
{
int bits = 0;
for (int j = i; j > 0; j= j - (j&-j))
bits++;
cout <<"Num: "<<i <<" Bits:"<<bits<<endl;
}
}
I hope I understood your question correctly. Hope that helps
Edit:
Ok, try this - this is dynamic programming without using every bit in every number:
void countBits(unsigned N) {
unsigned *arr = new unsigned[N + 1];
arr[0]=0;
for (int i = 1;i <=N; i ++)
{
arr[i] = arr[i - (i&-i)] + 1;
}
for(int i = 0; i <=N; i++)
cout<<"Num: "<<i<<" Bits:"<<arr[i]<<endl;
}
Hopefully, this works better
Several of the answers posted so far make use of bit shifting (just another word for division by 2) or
bit masking. This stikes me as a bit of a cheat. Same goes for using the '1' bit count in a 4 bit pattern then
matching by chunks of 4 bits.
How about a simple recursive solution using an imaginary binary tree of bits. each left branch contains a '0', each
right branch contains a '1'. Then do a depth first traversal counting the number of 1 bits on the way down. Once
the bottom of the tree is reached add one to the counter, print out the number of 1 bits found so far, back out
one level and recurse again.
Stop the recursion when the counter reaches the desired number.
I am not a C/C++ programmer, but here is a REXX solution that should translate without much imagination. Note
the magic number 32 is just the number of bits in an Unsigned long. Set it to anything
/* REXX */
SAY 'Stopping number:'
pull StopNum
Counter = 0
CALL CountOneBits 0, 0
return
CountOneBits: PROCEDURE EXPOSE Counter StopNum
ARG Depth, OneBits
If Depth = 32 then Return /* Number of bits in ULong */
if Counter = StopNum then return /* Counted as high as requested */
call BitCounter Depth + 1, OneBits /* Left branch is a 0 bit */
call BitCounter Depth + 1, OneBits + 1 /* Right branch is a 1 bit */
Return
BitCounter: PROCEDURE EXPOSE Counter StopNum
ARG Depth, OneBits
if Depth = 32 then do /* Bottom of binary bit tree */
say D2X(Counter) 'contains' OneBits 'one bits'
Counter = Counter + 1
end
call CountOneBits Depth, OneBits
return
Results:
Stopping number:
18
0 contains 0 one bits
1 contains 1 one bits
2 contains 1 one bits
3 contains 2 one bits
4 contains 1 one bits
5 contains 2 one bits
6 contains 2 one bits
7 contains 3 one bits
8 contains 1 one bits
9 contains 2 one bits
A contains 2 one bits
B contains 3 one bits
C contains 2 one bits
D contains 3 one bits
E contains 3 one bits
F contains 4 one bits
10 contains 1 one bits
11 contains 2 one bits
This answer is resonably efficient in time and space.
Can be done relatively trivially in constant time with the appropriate bit switching. No counting of 1s and no divisions. I think you were on the right track with keeping the array of known bit values:
int bits(int x)
{
// known bit values for 0-15
static int bc[16] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
// bit "counter"
int b = 0;
// loop iterator
int c = 0;
do
{
// get the last 4 bits in the number
char lowc = static_cast<char>(x & 0x0000000f);
// find the count
b += bc[lowc];
// lose the last four bits
x >>= 4;
++c;
// loop for each possible 4 bit combination,
// or until x is 0 (all significant bits lost)
}
while(c < 8 && x > 0);
return b;
}
Explanation
The following algorithm is like yours, but expands on the idea (if I understood your approach correctly.) It does not do any computation 'per number' as directed by the question, but instead uses a recursion that exists between sequences of lengths that are powers of 2. Basically, the observation is that for the sequence 0, 1,..,2^n-1 , we can use the sequence 0, 1, ...,2^(n-1)-1 in the following way.
Let f(i) be the number of ones in number i then f(2^(n-1)+i)=f(i)+1 for all 0<=i<2^(n-1). (Verify this for yourself)
Algorithm in C++
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
const int N = 32;
int* arr = new int[N];
arr[0]=0;
arr[1]=1;
for ( int i = 1; i < 15; i++ )
{
int pow2 = 1 << i;
int offset = pow2;
for ( int k = 0; k < pow2; k++ )
{
if ( offset+k >= N )
goto leave;
arr[offset+k]=arr[k]+1;
}
}
leave:
for ( int i = 0; i < N; i++ )
{
printf( "0x%8x %16d", i, arr[i] );
}
delete[] arr;
return EXIT_SUCCESS;
}
Note that in the for loop
for ( int i = 0; i < 15; i++ )
there may be overflow into negative numbers if you go higher than 15, otherwise use unsigned int's if you want to go higher than that.
Efficiency
This algorithm runs in O(N) and uses O(N) space.
Here is an approach that has O(nlogn) time complexity and O(1) memory usage. The idea is to get the Hex equivalent of the number and iterate over it to get number of ones per Hex digit.
int oneCount[] = { 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
int getOneCount(int n)
{
char inStr[70];
sprintf(inStr,"%X",n);
int i;
int sum=0;
for(i=0; inStr[i];i++)
{
if ( inStr[i] > '9' )
sum += oneCount[inStr[i]-'A' + 10];
else
sum+= oneCount[inStr[i] -'0'];
}
return sum;
}
int i,upperLimit;
cin>>upperLimit;
for(i=0;i<=upperLimit;i++)
{
cout << std::hex << " num = " << i << std::dec << " number of 1s = " << getOneCount(i) << endl;
}
enum bit_count_masks32
{
one_bits= 0x55555555, // 01...
two_bits= 0x33333333, // 0011...
four_bits= 0x0f0f0f0f, // 00001111....
eight_bits= 0x00ff00ff, // 0000000011111111...
sixteen_bits= 0x0000ffff, // 00000000000000001111111111111111
};
unsigned int popcount32(unsigned int x)
{
unsigned int result= x;
result= (result & one_bits) + (result & (one_bits << 1)) >> 1;
result= (result & two_bits) + (result & (two_bits << 2)) >> 2;
result= (result & four_bits) + (result & (four_bits << 4)) >> 4;
result= (result & eight_bits) + (result & (eight_bits << 8)) >> 8;
result= (result & sixteen_bits) + (result & (sixteen_bits << 16)) >> 16;
return result;
}
void print_range(unsigned int low, unsigned int high)
{
for (unsigned int n= low; unsigned int n<=high; ++n)
{
cout << std::hex << " num = " << xcount << std::dec << " number of 1s = " << popcount32(n) << endl;
}
}