I have a number of type int. It lies within [0,255]. That is, includes 8 bits. I need to check often say:
2(int) = 00000010(Binary)
1. The bit 6 and bit 7 must be equal to 0 and 1 respectively.
And I check it like this:
if ((!(informationOctet_ & (1 << 6))) && (informationOctet_ & (1 << 7)))
{
...
}
But it is not very readable, whether it is possible - to do something "beautiful"?
I can not use the std::bitset, my head says it's a waste of resources and you can not do without it.
There are two reasonable solutions: either set all don't-care bits to zero, and then test the result, or set the don't-care bits to one and test the result:
(x & 0xC0) == 0x80
(x | ~0xC0) == ~0x40
As harold pointed out in the comment, the first form is far more common. This pattern is so common that the optimizer of your compiler will recognize it.
Other forms exist, but they're obscure: ((x ^ 0x80) & 0xC0 == 0) works just as well but is less clear. Some ISA's cannot load large constants directly, so they use the equivalent of ((x>>6) & 0x3) == 0x2. Don't bother with this, your optimizer will.
You can apply some masking techniques as,
int i = 246; // Lets say any value.
int chk = ( i & 00000110b ); // eliminates all other bits except 6th & 7th bit
if (chk == 2) // because we want to check 6th bit is 0 & 7th is 1, that becomes 2 value in decimal
printf("The 6th bit is 0 & 7th bit is 1");
else
printf("Either 6th bit is not 0 or 7th bit is not 1, or both are not 0 & 1 respectivly");
Related
I am currently performing Fourier transforms for some physics problem, and a huge bottleneck of my algorithm comes from the evaluation of a scalar product modulo 2.
For a given integer N, I have to represent all the numbers in binary up to 2^N-1.
For each of these numbers, represented as a binary vector (e.g. 15 = 2^3 + 2^2 +2+2^0 = (1,1,1,1,0,...,0)) I have to evaluate its scalar products with all numbers from 0 to 2^N-1 in binary form modulo 2.
(for example, the scalar product 1.15 =(1,0,0,...,0).(1,1,1,1,0,...,0)=1*1+1*0+...=1 mod 2)
Note that the components are kept in binary form during the reducing modulo 2
(1,1).(1,1)=1*1+1*1 and not 1*1+2*2
This is basically 2^(2N) scalar products that I have to perform and reduce modulo 2.
I am having difficulty to get more than N = 18.
I was wondering whether some clever mathematical trick can be used to greatly reduce the time spent doing them.
I was thinking of some kind of recursion (i.e. saving results for N in a file and deduce the results for N+1) but I am not sure this would help. Indeed, with this recursion, knowing the results for N, I could cut the vector for N+1 corresponding to the N part plus an additional digit, but then at each scalar product, instead of evaluating the scalar product, I would have to tell my computer to go and read a big file (because I probably wouldn't be able to keep it all in dynamic memory), which is probably time-consuming, perhaps more than the ~20 multiplications I have to perform for each of the products.
Is there any known optimized number-theoretical algorithm allowing the evaluation of such a scalar product modulo 2 very quickly ? Are there any rules or ideas I am not aware of that I could exploit ?
Sorry for the terrible formatting, I just can't get LateX to work in here.
The sum of the product of corresponding bits, modulo 2, will be equal to the number of 1 bits in the AND of the two numbers, modulo 2.
As you can get the binary representation of a number easily, it might not be necessary to actually create an array of bits for them, but just use the integer data type in your programming language, which allows for at least 32 bits. Many languages offer bit operators, such as a AND (&) and XOR (^).
Counting the 1 bits in a number can be done with the variable-precision SWAR algorithm.
Here is program in Python that calculates this product modulo 2 for 2 numbers:
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
def product(a, b):
return numberOfSetBits(a & b) % 2
Instead of counting the bits with numberOfSetBits, you could fold the bits together with XORs, first the 16 most significant bits with the 16 least significant bits, then of that result the 8 most significant with the 8 least significant bits, until you have one bit left. Again in Python:
def bitParity(i):
i = (i >> 16) ^ i
i = (i >> 8) ^ i
i = (i >> 4) ^ i
i = (i >> 2) ^ i
i = (i >> 1) ^ i
return i % 2
def product(a, b):
return bitParity(a & b)
If you change the order that you are evaluating these pairs (a matrix of size 2n x 2n), then you can efficiently figure out which products-mod-2 change in each row of your evaluation.
Using Gray code, you can iterate over each value from 0 ... 2n-1 in a special order where only 1 bit of the outer-loop value changes each time. You can store 1 bit for each value from 0 ... 2n-1 representing the previous row's product-mod-2 values, and then change it based on whether the changing bit has any effect, which it only does when the corresponding bit in the other (inner loop) number is 1 (if it's 0 then the binary AND will be 0 no matter what the value of the other bit).
In C:
int N = 5;
int max = (1 << N) - 1;
unsigned char* prev = calloc((1 << N) / 8, 1);
// for the first row all the products will be zero, so start at row 1
for(int a = 1; a <= max; a++)
{
int grey = a ^ (a >> 1); // compute the grey code
int prev_grey = (a - 1) ^ ((a - 1) >> 1);
int changed_bit = grey ^ prev_grey;
for(int b = 0; b <= max; b++)
{
// the product will be changed only if b has a 1 at the same place
// (otherwise it will be 0 regardless)
if(b & changed_bit)
{
prev[b >> 3] ^= (1 << (b & 7));
}
int mod = (prev[b >> 3] & (1 << (b & 7))) != 0;
printf("mod value of %d and %d is %d\n", grey, b, mod);
}
}
The inner loop can be optimized even more because you can easily figure out which values of b have a non-zero value in the position of the changed bit: for example if it's in position 10 then there will be runs of 1024 in a row of 0 then 1 etc. So you know that you have 1024 values where the product-mod-2 is the same as in the previous row etc. It's not clear to me if this helps you though because I don't know what you are doing with these products.
The inner loop could also be unrolled (e.g. 32 or 64 times) so that you don't read and write to the prev array each time, but rather process blocks of 32 or 64 bits at a time.
I have seen this question in a site that shows interview questions from Google.
I have no idea how to solve this question.
If we are allowed to keep some other variables, then I would suggest to keep 2 indices, 1 point to the beginning and the other to the end. And then use the bit variable to compare the 2 of them (by bit manipulation).
But if we are not allowed to use any more variables, I have no clue how to solve it.
For numbers of 2n bits to be a palindrome it is necessary that each bit at position i equals the bit at index (2n-i).
Using exclusive or (XOR) single bits can easily be compared:
a XOR b == 1 if, and only if, bits a and b are not equal.
So when one compares every corresponding pair of bits (see above) this way and builds the result by ORing all the single-bit comparison results it wil be 0 for palindromes and 1 for any other number.
I'm assuming we're talking about bit-wise palindromic (i.e. 3 = 11 is, but 2 = 10 is not).
I see there being two possibilities:
(I've written some Java code for each. Some brackets only included for readability)
Indices don't count as variables.
The first thing I'd say is probably "But indices are variables...".
We can just loop over the number and return once we get a mismatch.
digits below is a variable, but just for readability - it can trivially be substituted into the if-statement.
The formula for digits came about after some playing around (there may be a simpler way).
boolean isPalidrome(int number)
{
int digits = (int)Math.ceil(Math.ceil(Math.log10(1+number)/Math.log10(2)))-1;
for (int i = 0; number/2 >> i != 0; i++)
{
if (((number >> i) & 1) != (((number >> digits - i) & 1)))
return false;
}
return true;
}
Indices do count as variables.
This can be done by essentially unrolling the above loop, assuming we're given a fixed-size number (such as int, which is 32 bits).
I changed the type to byte as I didn't really see the point of essentially duplicating that many lines. byte only has 8 bits, so we only need 4 checks, with break conditions.
Again digits is a variable, but doesn't need to be.
boolean isPalidrome(byte number)
{
int digits = (int)Math.ceil(Math.ceil(Math.log10(1+number)/Math.log10(2)))-1;
if ((number & 1) != (((number >> digits) & 1)))
return false;
if ((number/2 >> 1) == 0)
return true;
if (((number >> 1) & 1) != (((number >> (digits - 1)) & 1)))
return false;
if ((number/2 >> 2) == 0)
return true;
if (((number >> 2) & 1) != (((number >> (digits - 2)) & 1)))
return false;
if ((number/2 >> 3) == 0)
return true;
if (((number >> 3) & 1) != (((number >> (digits - 3)) & 1)))
return false;
return true;
}
The above could also be stuck into a single statement if need be.
If we're allowed to modify the actual number, it may also be possible to check the first and last bits, as done above, but then modify the number to strip off the first and last bits, so we can just check the first and last bits again, until the number is zero.
Live demo.
Note how none of the above uses a bit variable. Perhaps the bit variable is simply meant to be a flag to keep track of whether or not the number is a palindrome.
This is part of a search function on a website. So im trying to find a way to get to the end result as fast as possible.
Have a binary number where digit order matters.
Input Number = 01001
Have a database of other binary numbers all the same length.
01000, 10110, 00000, 11111
I dont know how to write what im doing, so im going to do it more visually below.
// Zeros mean nothing & the location of a 1 matters, not the total number of 1's.
input num > 0 1 0 0 1 = 2 possible matches
number[1] > 0 1 0 0 0 = 1 match = 50% match
number[2] > 1 0 1 1 0 = 0 match = 0% match
number[3] > 0 0 0 0 0 = 0 match = 0% match
number[4] > 1 1 1 1 1 = 2 match = 100% match
Now obviously, you could go digit by digit, number by number and compare it that way (using a loop and what not). But I was hoping there might be an algorithm or something that will help. Mostly because in the above example I only used 5 digit numbers. But im going to be routinely comparing around 100,000 numbers with 200 digits each, that's a lot of calculating.
I usually deal with php and MySQL. But if something spectacular comes up I could always learn.
If it's possible to somehow chop up your bitstrings in integer-size chunks some elementary boolean arithmetic would do, and that kind of instructions is generally pretty fast
$matchmask = ~ ($inputval ^ $tomatch) & $inputval
What this does:
the xor determines the bits that are different in the inputval and tomatch
negation gives a value where all bits that are equal in inputval and tomatch are set
and that with inputval and only the bits that are 1 in both inputval and tomatch remain set.
Then count the number of bits set in the result, look at How to count the number of set bits in a 32-bit integer? for an optimal solution, easily translated into php
Instead of checking each bit, you could pre-process the input and determine which bits need checking. In the worst case, this devolves into processing each bit, but for a normal distribution, you'll save some processing.
That is, for input
01001, iterate over the database and determine if number1[0] & input is non-zero, and (number1[3] >> 8) & input is non-zero, assuming 0 as the index of the LSB. How you get fast bit-shifting and anding with the large numbers is on you, however. If you detect 1s than 0s in the input, you could always invert the input and test for zero to detect coverage.
This will give you modest improvement, but it's at best a constant-time reduction of the problem. If most of your inputs are balanced between 0s and 1s, you'll halve the number of required operations. If it's more biased, you'll get better results.
Well, the first thing I can think of is a simple bitwise AND between the two numbers; you can then analyze the result to get the match percentage:
if( result >= input )
//100% match
else {
result ^= input;
/* The number of 1's in result is the number of 1 of "input"
* that are missing in "result".
*/
}
Of course, you'll need to implement your own AND and XOR function (this will work only for 32 bit integers). Note that it works only with unsigned numbers.
Suppose the input number is called A (so in your example A = 01001) and the other number is x. You'll have 100% match when x & A == A. Otherwise, for partial matches, the number of 1 bits will be (taken from hacker's delight):
x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x >>16) & 0x0000FFFF);
Note this will work for 32 bits integers.
Let's assume you have a function bit1count, then from what you describe, the "likeness" formula should be:
100.0 / min(bit1count(n1), bit1count(n2)) * bit1count(n1 & n2)
With n1 and n2 being the two numbers and & being the logical and operator.
bit1count can be easily implemented using a loop, or, more elegant, using the algorithm provided in BigBears answer.
There is actually a BIT_COUNT in mysql, so something like this should work:
SELECT 100.0 / IF(BIT_COUNT(n1) < BIT_COUNT(n2), BIT_COUNT(n1), BIT_COUNT(n2)) * BIT_COUNT(n1 & n2) FROM table
I'm looking for an innovative way to check if a number has only one on bit in a signed int.
I am well aware that I can simply do a loop with a counter, some modular division, and a bit shift. But I'm curious if there is a better way since we are only looking for ONE bit to be on.
bool HasOnlyOneBit (int numb)
{
//return true if numb has only one bit (I.E. is equal to 1, 2, 4, 8, 16... Int.MinValue)
}
return x == (x & -x);
This answer works because of the way two's complement notation is designed.
First, an example. Assume we have 8-bit signed integers.
00010000 = 16
11110000 = -16
The bitwise and will give you 00010000 as a result, equal to your original value! The reason that this works is because when negating in 2's complement, first invert all the bits, then add 1. You'll have a bunch of zeros and a bunch of carries until a one falls into place. The bitwise and then checks if we have the right bit set.
In the case of a number that isn't a power of two:
00101010 = 42
& 11010110 = -42
----------
00000010 != 42
Your result will still have only a single bit, but it won't match the original value. Therefore your original value had multiple bits set.
Note: This technique returns true for 0, which may or may not be desirable.
This is a famous problem
(x & x-1) == 0
Power of 2 from Wiki : here
64 = 01000000 (x)
63 = 00111111 (x-1)
______________
& = 00000000 == 0
______________
Case when some other bits are ON
18 = 00010010 (x)
17 = 00010001 (x-1)
______________
& = 00010000 != 0
______________
I'd recommend you take a look at the Bit Twiddling Hacks page and choose the most suitable option under "Determining if an integer is a power of 2" or "Counting bits set".
return (x && ((x & x-1) == 0))
return (x && (0x8000000000000000ULL % x));
This is a simplification of the following code:
if (x == 0) {
return false;
} else if (0x8000000000000000ULL % x) {
return false;
} else {
return true;
}
Explanation: 0x8000000000000000 is the highest "1 bit only" value for an 64 bit register. Only a division by an other "1 bit only" value will result in no remainder.
Take the log to base 2 of your number, if it's an integer your number has only 1 1 bit. Not sure that I think this is better than any of your excluded options.
Python3 memory-efficient solution
return n > 0 and (n & (n-1)) == 0
Do the below without any conditional or comparison operator.
if (Number <= 0)
{
Print '0';
}
else
{
print Number;
}
thanks..
My original simple solution:
1. print( (abs(Number)+Number) / 2 )
That solution would work in most cases, unless Number is very large (more than half the maximum e.g. Number >= MAX_INT/2) in which case the addition may cause overflow.
The following solution solves the overflow problem:
2. print( (abs(Number)/2) + (Number/2) )
However, there may be a case in which Number is and must remain integer, and the division operator (/) is integer division, so that 7/2=3. In this case solution 2 won't work because if Number=7 it will print 6 (for this case solution 1 will work just fine).
So if we need to deal with both large numbers AND integer arithmetic, the following monstrosity comes to the rescue, adding compensation for the 1 that may be lost in the division by 2 in case of odd integer:
3. print(
( (abs(Number)/2)+(Number/2) ) +
((
(Number-(2*(Number/2))) +
(abs(Number)-(2*(abs(Number)/2)))
) / 2)
)
print max(0, number)
Let's say that number is represented by an 8-bit two's complement integer.
Positive numbers including 0 all have the MSB set to 0.
Negative numbers all have the MSB set to 1.
So we take the complement of the MSB, extend it to the full 8 bits, and bitwise AND it with the original number, e.g.
Positive:
00110101 -> MSB is 0
11111111 -> complement of MSB extended
00110101 -> bitwise AND of above
Negative:
10110101 -> MSB is 1
00000000 -> complement of MSB extended
00000000 -> bitwise AND of above
No comparisons needed - I'm kind of assuming that bitwise AND isn't strictly a comparison.
Also, sorry for the lack of code, but you get the idea.
I haven't seen a solution yet that is valid for the complete domain.
An other solution is to call a function that raises an exception if the input value is 0 or below 0. Then catch the exception and print 0.
Or you can use a function Sign, that returns -1 if the input is <0, 0 if it's 0 and 1 otherwise.
print ((sign(x)+1) * sign(x) / 2) * x.
sign can be -1, 0 or 1, so ((sign(x)+1) * sign(x) / 2) can have the following values:
-1 -> ((-1+1)*-1)/2 = 0
0 -> ((0+1)*0)/2 = 0
1 -> ((1+1) * 1)/2 = 1
Another method is to create a lookup table that maps all non negative numbers to themself and the rest to 0.
But, in my opinion, the original function is much clearer. So why violate the KISS principle.
Similar to the accepted answer. Although acceptable where absolute value is implemented using comparisons, but also more prone to overflow:
print( (sqrt(Number * Number) + x) / 2);
Assuming C or C++:
switch ((unsigned long)Number & ~(unsigned long)LONG_MAX) {
case 0:
printf("%d\n", Number);
break;
default:
printf("0\n", Number);
break;
}
If you consider switch to be a conditional operator, then try this:
unsigned long flag = (unsigned long)Number & ~(unsigned long)LONG_MAX;
flag /= (unsigned long)LONG_MAX + 1;
flag = 1 - flag;
printf("%d\n", Number * flag);