Write a function to copy 0-15 bits into 16-31 [closed] - c++

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 7 years ago.
Improve this question
How to write a function to copy 0-15 bits into 16-31?
unsigned int n = 10; // 1010
copyFromTo(n);
assert(n == 655370);
n = 5;
copyFromTo(n);
assert(n == 327685);
n = 134;
copyFromTo(n);
assert(n == 8781958);

You want to copy the bits in 0-15 to 16-31. You should understand that multiplying by 2 is equivalent to shifting the bits of the number once to the left (moving to higher bits).
If your number is n, n << 16 would be shifting your number 16 bits to the left. This is equivalent to multiplying n with the 16th power of 2, which happens to be 65536.
To copy the bits, and keep the original bits in 0-15, the command n = n + (n << 16); should work. However, the issue with this is (as pointed out in the comments), that the upper 16-31 bits are still set in n + term. We also need to clear these bits. Note that 65535 corresponds to 2^16 - 1, and would have the first 0-15 bits as 1, and others as 0. So the correct command would be n = (n && 65535) + (n << 16);

This will do it:
void copyFromTo(unsigned int& n)
{
n = (n & 0xffff) * 0x00010001;
}

n << 16 to shift bits would do it, to move lower bits to upper? (edited) And after that, copying just the lower 16 bits into it

Related

A direct way to turn bits according to mask [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Suppose we have a byte B and a mask M such that one of the bits in the mask is either 1 or 0 and the others are 0, (suppose we know which bit that is, it can be any bit but for simplicity it's the LSB). We want that the same bit in B will have the same value as that bit from M.
For example if B=1111, M=0000 then we want to have after the operation B=1110, but if M was M=0001 then B would have been B=1111.
I'm basically asking how to implement the boolean function generated from this truth table:
old new result
0 0 0
0 1 1
1 0 0
1 1 1
So result would be:
a=old, b= new
result=a'b+ab
Doing B = ~B&M | B&M; in C doesn't seem to work...
I probably can do it with conditionals but there's got to be a way to it without them.
Another example:
If we care about the second bit, and if B=0001, M=0010 then the result of the operation would be 0011. But if M was M=0000 then the result of the operation was 0001.
I know how to set clear and toggle a bit, this is not what I'm asking.
You need to specify the offset to the bit you care about (e.g. index):
char AssignBit(unsigned char byte, unsigned char mask, int index)
{
unsigned char cleared = byte & ~(1 << index);
unsigned char assigned = cleared | mask & (1 << index);
return assigned;
// or simply:
return byte & ~(1 << index) | mask & (1 << index);
// if it is guaranteed that at most one bit is set in mask, this also works:
return byte & ~(1 << index) | mask;
}
If I undestand correctly, you want to set a single bit from B to the value of that bit in M, and you don't care what the previous value in B was. M is not really a mask in this case; your mask is given by the bit number. So you'd do something like
unsigned mask = (1<<BITNUM);
unsigned result = (~mask & B) | (mask & M)
where BITNUM = 0 if it's the LSB.
It can't be implemented as a boolean function, as the operators you want to use are bit-wise, and so the operands are multi-bit. But you can incorporate some bit-shifts to accommodate that:
#define BIT_NUMBER 3 // For example
B &= ~(1 << BIT_NUMBER); // Zero out the bit
B |= M << BIT_NUMBER; // Set to M's bit value
For example if B=1111, M=0000 then we want to have after the operation
B=1110
The problem is that you haven't specified which bit in M is significant, and there's no way to determine the significant bit from the value of M.
You actually need three quantities, the byte B, the value V (which you're calling M), and a mask M (which is missing from your question).
Here's the code that combines the three:
result = (B & ~M) | (V & M);
How to change the nth bit to x:
number ^= (-x ^ number) & (1 << n);
(Taken from https://stackoverflow.com/a/47990/6149078)

Implement bit vector using bitwise logical operations

This question is asked on Pearls of programming Question 2. And I am having trouble understanding its solution.
Here is the solution written in the book.
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1 + N/BITSPERWORD];
void set(int i) { a[i>>SHIFT] |= (1<<(i & MASK)); }
void clr(int i) { a[i>>SHIFT]&=~(1<<(i & MASK)); }
int test(int i) { return a[i>>SHIFT]&(1<<(i & MASK)); }
I have ran this in my compiler and I have looked at another question that talks about this problem, but I still dont understand how this solution works.
Why does it do a[i>>SHIFT]? Why cant it just be a[i]=1; Why does i need to shifted right 5 times?
32 is 25, so a right-shift of 5 bits is equivalent to dividing by 32. So by doing a[i>>5], you are dividing i by 32 to figure out which element of the array contains bit i -- there are 32 bits per element.
Meanwhile & MASK is equivalent to mod 32, so 1<<(i & MASK) builds a 1-bit mask for the particular bit within the word.
Divide the 32 bits of int i (starting form bit 0 to bit 31) into two parts.
First part is the most significant bits 31 to 5. Use this part to find the index in the array of ints (called a[] here) that you are using to implement the bit array. Initially, the entire array of ints is zeroed out.
Since every int in a[] is 32 bits, it can keep track of 32 ints with those 32 bits. We divide every input i with 32 to find the int in a[] that is supposed to keep track of this i.
Every time a number is divided by 2, it is effectively right shifted once. To divide a number by 32, you simply right shift it 5 times. And that is exactly what we get by filtering out the first part.
Second part is the least significant bits 0 to 4. After a number has been binned into the correct index, use this part to set the specific bit of the zero stored in a[] at this index. Obviously, if some bit of the zero at this index has already been set, the value at that index will not be zero anymore.
How to get the first part? Right shifting i by 5 (i.e. i >> SHIFT).
How to get the second part? Do bitwise AND of i by 11111. (11111)2 = 0x1F, defined as MASK. So, i & MASK will give the integer value represented by the last 5 bits of i.
The last 5 bits tell you how many bits to go inside the number in a[]. For example, if i is 5, you want to set the bit in the index 0 of a[] and you specifically want to set the 5th bit of the int value a[0].
Index to set = 5 / 32 = (0101 >> 5) = 0000 = 0.
Bit to set = 5th bit inside a[0]
= a[0] & (1 << 5)
= a[0] & (1 << (00101 & 11111)).
Setting the bit for given i
Get the int to set by a[i >> 5]
Get the bit to set by pushing a 1 a total of i % 32 times to the left i.e. 1 << (i & 0x1F)
Simply set the bit as a[i >> 5] = a[i >> 5] | (1 << (i & 0x1F));
That can be shortened to a[i >> 5] |= (1 << (i & 0x1F));
Getting/Testing the bit for given i
Get the int where the desired bit lies by a[i >> 5]
Generate a number where all bits except for the i & 0x1F bit are 0. You can do that by negating 1 << (i & 0x1F).
AND the number generated above with the value stored at this index in a[]. If the value is 0, this particular bit was 0. If the value is non-zero, this bit was 1.
In code you would simply, return a[i >> 5] & (1 << (i & 0x1F)) != 0;
Clearing the bit for given i: It means setting the bit for that i to 0.
Get the int where the bit lies by a[i >> 5]
Get the bit by 1 << (i & 0x1F)
Invert all the bits of 1 << (i & 0x1F) so that the i's bit is 0.
AND the number at this index and the number generated in step 3. That will clear i's bit, leaving all other bits intact.
In code, this would be: a[i >> 5] &= ~(1 << (i & 0x1F));

How to set the highest-valued 1 bit to 0 , prefferably in c++ [duplicate]

This question already has answers here:
What's the best way to toggle the MSB?
(4 answers)
Closed 8 years ago.
If, for example, I have the number 20:
0001 0100
I want to set the highest valued 1 bit, the left-most, to 0.
So
0001 0100
will become
0000 0100
I was wondering which is the most efficient way to achieve this.
Preferrably in c++.
I tried substracting from the original number the largest power of two like this,
unsigned long long int originalNumber;
unsigned long long int x=originalNumber;
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
x >>= 1;
originalNumber ^= x;
,but i need something more efficient.
The tricky part is finding the most significant bit, or counting the number of leading zeroes. Everything else is can be done more or less trivially with left shifting 1 (by one less), subtracting 1 followed by negation (building an inverse mask) and the & operator.
The well-known bit hacks site has several implementations for the problem of finding the most significant bit, but it is also worth looking into compiler intrinsics, as all mainstream compilers have an intrinsic for this purpose, which they implement as efficiently as the target architecture will allow (I tested this a few years ago using GCC on x86, came out as single instruction). Which is fastest is impossible to tell without profiling on your target architecture (fewer lines of code, or fewer assembly instructions are not always faster!), but it is a fair assumption that compilers implement these intrinsics not much worse than you'll be able to implement them, and likely faster.
Using an intrinsic with a somewhat intellegible name may also turn out easier to comprehend than some bit hack when you look at it 5 years from now.
Unluckily, although a not entirely uncommon thing, this is not a standardized function which you'd expect to find in the C or C++ libraries, at least there is no standard function that I'm aware of.
For GCC, you're looking for __builtin_clz, VisualStudio calls it _BitScanReverse, and Intel's compiler calls it _bit_scan_reverse.
Alternatively to counting leading zeroes, you may look into what the same Bit Twiddling site has under "Round up to the next power of two", which you would only need to follow up with a right shift by 1, and a NAND operation. Note that the 5-step implementation given on the site is for 32-bit integers, you would have to double the number of steps for 64-bit wide values.
#include <limits.h>
uint32_t unsetHighestBit(uint32_t val) {
for(uint32_t i = sizeof(uint32_t) * CHAR_BIT - 1; i >= 0; i--) {
if(val & (1 << i)) {
val &= ~(1 << i);
break;
}
}
return val;
}
Explanation
Here we take the size of the type uint32_t, which is 4 bytes. Each byte has 8 bits, so we iterate 32 times starting with i having values 31 to 0.
In each iteration we shift the value 1 by i to the left and then bitwise-and (&) it with our value. If this returns a value != 0, the bit at i is set. Once we find a bit that is set, we bitwise-and (&) our initial value with the bitwise negation (~) of the bit that is set.
For example if we have the number 44, its binary representation would be 0010 1100. The first set bit that we find is bit 5, resulting in the mask 0010 0000. The bitwise negation of this mask is 1101 1111. Now when bitwise and-ing & the initial value with this mask, we get the value 0000 1100.
In C++ with templates
This is an example of how this can be solved in C++ using a template:
#include <limits>
template<typename T> T unsetHighestBit(T val) {
for(uint32_t i = sizeof(T) * numeric_limits<char>::digits - 1; i >= 0; i--) {
if(val & (1 << i)) {
val &= ~(1 << i);
break;
}
}
return val;
}
If you're constrained to 8 bits (as in your example), then just precalculate all possible values in an array (byte[256]) using any algorithm, or just type it in by hand.
Then you just look up the desired value:
x = lookup[originalNumber]
Can't be much faster than that. :-)
UPDATE: so I read the question wrong.
But if using 64 bit values, then break it apart into 8 bytes, maybe by casting it to a byte[8] or overlaying it in a union or something more clever. After that, find the first byte which are not zero and do as in my answer above with that particular byte. Not as efficient I'm afraid, but still it is at most 8 tests (and in average 4.5) + one lookup.
Of course, creating a byte[65536} lookup will double the speed.
The following code will turn off the right most bit:
bool found = false;
int bit, bitCounter = 31;
while (!found) {
bit = x & (1 << bitCounter);
if (bit != 0) {
x &= ~(1 << bitCounter);
found = true;
}
else if (bitCounter == 0)
found = true;
else
bitCounter--;
}
I know method to set more right non zero bit to 0.
a & (a - 1)
It is from Book: Warren H.S., Jr. - Hacker's Delight.
You can reverse your bits, set more right to zero and reverse back. But I do now know efficient way to invert bits in your case.

Check if the binary of a number has equal no of 0's and 1's [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
We are given a integer number, and the task is to tell whether the binary representation of the number includes equal number of binary 1's and 0's or not?
I want the solution in constant time.
I have the code for calculating no of 1s with the help of hamming weight algorithm!
Please help i want to count no of 0's!!
In production code (I mean if not restricted by rules dictated in an assignment) I'd do it like this:
#include <iostream>
#include <bitset>
int main()
{
int k(24); // an example integer - the one you check for equality of 0's and ones
std::bitset<32> bs(k); // I suppose 32 bit numbers - choose your own length
if ( 16 == bs.count() ) // 16 is half the bit length - count returns the bits that are swithced ON
{
std::cout << "Equal number of 1s and 0s\n";
}
}
I mean after all the question is tagged c++
If x - is your number, N1 is the number of "1" then
int N0 = ceil(log2(x)) - N1;
will calculate number of "0". Do not forget
#include <math.h>
int numberOfZeros = numberOfBinaryDigits - numberOfOnes;
Where number of binary digits is either based on the storage used for the data, or log2.
32 bit integer examples:
Using bit operators (and multiply):
int bitcount(unsigned int i)
{
// generate a bit count in each pair of bits
i = i - ( (i >> 1) & 0x55555555);
// generate a bit count in each nibble
i = (i & 0x33333333) + ( (i >> 2) & 0x33333333 );
// sum up the bits counts in the nibbles
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
Using gcc popcount:
int bitcount(unsigned int i)
{
return(__builtin_popcount(i));
}
using visual studio popcnt:
int bitcount(unsigned int i)
{
return(_popcnt(i));
}
// if(16 == bitcount(i)), then equal number of 1's and 0's.

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.