Rethink DB Bitwise comparison - bit-manipulation

I'm trying to filter a rethinkdb selection based on some bits in a field
I've tried doing
r.db("db").table("table").filter(r.expr(r.row("flags") & 64).ne(0))
// and
r.db("db").table("table").filter(r.row("flags") & 64)
64 being the one to test, with no luck, nothing is returned. I've tried doing the tests without calling rows, and it works just fine
r.db("db").table("table").filter(114 & 64)
// or
r.db("db").table("table").filter(r.expr(114 & 64).ne(0))
that returns either all the entries, or none. I want to only get the entries where the bit test does not equal 0

rethinkdb does not have the bitwise AND operator by default, but it can execute arbitrary javascript as filter function as follows:
r.db("db").table("table").filter(
r.js('(function (row) { return (row.flags & 64) != 0; })')
)

Related

Bitwise operators and bit manipulation (no solution?)

I've been racking my brain trying to come up with a solution, but am stuck.
I have a function, this function takes the input (either 0b0, 0b1, or 0b10) and sets the bit of some variable - or at least it's supposed to.
The value it's changing has two states: either 0b100 or 0b101. I want to set the respective bit from the input. This is easy for the true bits, but tricky for the false bits. Some pseudo code for all the scenarios:
if (var == 0b100 && input == 0b0) { do nothing } // bit already set
if (var == 0b101 && input == 0b0) { var = 0b100 } // bit is different, so we set it.
if (var == 0b100 && input == 0b1) { var = 0b101 } // bit is different, so we set it.
if (var == 0b101 && input == 0b1) { do nothing } // bit is already set
if (var == 0b100 && input == 0b10) { var = 0b110 } // bit is never set, so set it
if (var == 0b101 && input == 0b10) { var = 0b110 } // bit is never set, so set it
I don't want to cheat and make a separate statement for every possibility, I'd like a function for this. Here's what I've sort of strung together, but it obviously doesn't work:
if ( var ^ input )
{
var ^= input;
}
The issue with this code is that 3rd bit (far left one) is always true.
Is this even possible?
EDIT:
Here is the same question, just posed a different way (which will result in different answers).
A function takes input for one bit. I want to take the left most bit and compare that bit and only that bit to another variable. e.g. input = 0b10 compared to 0b101's second bit, 0b00, since 0b10's left most bit is the second one.
On rare occasion, the unchanging bit may change :P (not from me though), so 0b001 or 0b000 may be it's value. For this reason, I cannot create a dynamic mask and compare only my bit.. The best method to solve my issue would be to answer this alternative question. Thanks a ton for your help, guys!
Step 1: Mask out the lower two bits.
var &= 0b100;
Step 2: Assign the lower two bits through OR operation.
var |= input;
Note that you may need to change the bit mask in step 1 in actual code base on the actual data type.

Understanding "Bitwise-And (&)" and "Unary complement(~)" in c++

I have some trouble understanding Bitwise-And and Unary Complement when both are used in this code snippet
if((oldByte==m_DLE) & (newByte==m_STX)) {
int data_index=0;
//This below line --- does it returns true if both the oldByte and newByte are not true
//and within timeout
while((timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))) {
if(Serial.available()>0) {
oldByte=newByte;
newByte=Serial.read();
if(newByte==m_DLE) {
.
.
.
are the both operators & ~are performing a logical not operation like checking until if both oldByte and newByte are false
The above code is from the link --> line 227 of the code
I am trying to use the implement the code for my application in C but without the timing functions
if((oldByte==DLE) && (newByte== STX)) {
data_index = 0;
// is this the correct implematation for above C++ code to C
while(! ((oldByte== DLE) && (newByte== ETX))){
oldByte = newByte;
Is this method correct for implementing in C
(timeout.read_s()<m_timeout) & ~((oldByte==m_DLE) & (newByte==m_ETX))
is equivalent to (but probably less readable than)
(timeout.read_s()<m_timeout) && !(oldByte==m_DLE && newByte==m_ETX)
which is equivalent to (and IMO less readable than)
(timeout.read_s()<m_timeout) && (oldByte!=m_DLE || newByte!=m_ETX)
Edit: should add a caveat about short-circuiting. Although the particular example statements will all return the same value, using && or || will skip evaluating pieces that can't impact the result. This isn't important in your specific example, but could be very important in an example like this:
(oldByte!=nullptr & *oldByte == m_ETX) // will crash when oldByte=nullptr.
(oldByte!=nullptr && *oldByte == m_ETX) // will evaluate to false when oldByte=nullptr.
Since the equality-operator (==) yields 0 or 1 as a result, you can use bitwise and, too. (foo==1) & ~(bar==1) works too, since the AND with (foo==1), which always results in 1 and 0, masks all other bits in ~(bar==1). However, it is strongly recommended to use the logical counterparts &&, || and !.
The following would not work as expected:
if (~(bar == 1) & ~(foo == 1))
e.g. if foo = bar = 1, then it would evaluate to 0xfffffffe on ia32, which is different from 0 and therefore "TRUE"

Unit testing with generated inputs and expected outputs

I'm writing some simple unit tests for a method which acts like a database query: it returns a list of results that can be customised using a limit (max of n results) and a page (the p'th set of n results). I'd like to test a few cases, such as:
Return all the results
Return the first page of a limited result set
Return an aribtrary page of a limited result set
Return the last page of a limited result set which overruns the total number of results
Return a page beyond the total number of results
I need to mock the results (effectively names) that are returned, so I'm just generating them with a counter to make a list of "Name #1", "Name #2", etc. for as many as I need. Each test looks (roughly) like:
public void testGetMockCandidatesLimited() throws Exception {
int numResults = 4;
setupMock(numResults);
results = queryFunction(...);
// Check that the expected number of results was returned
assertEquals(numResults, results.size());
// Check that the results are correct and in order
for (int i = 0; i < numResults; i++) {
assertEquals(result.get(i).getName(), "Name #" + (i + 1));
}
}
My question is: is it okay to 'generate' the expected answers in this way? This is a trivial example, but the next step was to write a test to write a test to get the second page of two results each, and I had:
final int TEST_LIMIT = 2, TEST_PAGE = 1;
// Check that the expected number of results was returned
assertEquals(numResults, results.size());
// Check that the results are correct and in order
for (int i = TEST_LIMIT * TEST_PAGE; i < TEST_LIMIT * TEST_PAGE + TEST_LIMIT; i++) {
assertEquals(result.get(i).getName(), "Name #" + (i + 1));
}
Now it just so happens that this test is 'correct' in the sense that i will take on the values that I expect it to and ensure that the results are "Name #3" and "Name #4". However it also happens that my queryFunction calculates which results to return in the same way (limit * page + limit kind of thing).
This is concerning because if the test generates the expected answers in the same way that the unit under test does, it won't detect if there's a bug in that approach. However naming the input values with constants makes the tests much more readable than just have magic integers between 1 and 4 plugged in everywhere.
What is the best way to deal with this situation, for both readability and maintainability (e.g. changing values in the future, should you need to)?
In asking this question I think I've convinced myself that the solution is to define the expected values as constants up front as well, such as:
final int LIMIT = 2, PAGE = 1, MIN_RESULT = 3, MAX_RESULT = 4;
... and then use those values in the assertions. This retains all the readability of named key values, and discourages the temptation to generate the expected outputs. In this case I would still be using a loop to generate each expected name between Name #MIN and Name #MAX, but the bounds themselves would be explicitly static.
Is this as good as it gets, or are there better ways to deal with this repetitiveness?

What does this c++ statement check? (Box2d)

if ((catA & maskB) != 0 && (catB & maskA) != 0)
It is in Box2d's manual: 6.2, and is used to check if two objects should collide (after filtering)
It checks that catA has at least one common '1' bit with maskB, and catB has at least one common '1' bit with maskA.
For example, if catA is 3 (binary 00000011) and maskB is 10101010), then (catA & maskB) != 0 is true because catA & maskB is 00000010.
This is called masking, which means only keeping bits of interest.
You frequently have this kind of construct :
#define READ 1
#define WRITE 2
#define READWRITE (READ|WRITE)
#define DIRECTORY 4
int i=getFileInfo("myfile");
if(i & READWRITE)puts("you can read or write in myfile");
if(i & DIRECTORY)puts("myfile is a directory");
BTW, "i & DIRECTORY" means the same as "(i & DIRECTORY) != 0"
catA is a bit field of collision categories for object A
maskA is a bit field of categories that object A can collide with.
For example:
catA = 100010000010010 // Object A is in 4 collision categories
maskA = 001010000000000 // Object A can collide with too different categories
catB = 000010001000001 // Object B is in 3 collision categories
maskB = 100000000000000 // Object B can only collide with the category represented by the highest bit
catA & maskB means the bits that are 1 in both catA and maskB, so 1000000000000000. It's not 0, because Object B can collide with objects in the highest bit, and object A has that bit set.
catB & maskA means the bits that are 1 in both catB and maskA, so 0000100000000000. It's also not zero since Object A can collide with objects in the 5th highest bit category, and Object B is in that category.
So the two objects can collide.
the symbol & is the bitwise AND operator. Therefore, the statement
(catA & maskB) != 0
checks to see if any bits overlap in both of those items. It looks at if it checks A against B first, then B against A.
I know many C/C++ programmers love terseness but I find this type of code can be made much more readable by moving this test into a function (you can inline it if you want). They could also have gotten rid of the comment by moving the code to a well named method.
if (FixturesCanCollide() )
{
}
You can actually throw away the comparison to !=0 (although you might prefer it for clarity, either way it probably compiles down to the same code.
inline bool FixturesCanCollide()
{
return (catA & maskB) && (catB & maskA);
}

evaluate whether a number is integer power of 4

The following function is claimed to evaluate whether a number is integer power of 4. I do not quite understand how it works?
bool fn(unsigned int x)
{
if ( x == 0 ) return false;
if ( x & (x - 1) ) return false;
return x & 0x55555555;
}
The first condition rules out 0, which is obviously not a power of 4 but would incorrectly pass the following two tests. (EDIT: No, it wouldn't, as pointed out. The first test is redundant.)
The next one is a nice trick: It returns true if and only if the number is a power of 2. A power of two is characterized by having only one bit set. A number with one bit set minus one results in a number with all bits previous to that bit being set (i.e. 0x1000 minus one is 0x0111). AND those two numbers, and you get 0. In any other case (i.e. not power of 2), there will be at least one bit that overlaps.
So at this point, we know it's a power of 2.
x & 0x55555555 returns non-zero (=true) if any even bit it set (bit 0, bit 2, bit 4, bit 6, etc). That means it's power of 4. (i.e. 2 doesn't pass, but 4 passes, 8 doesn't pass, 16 passes, etc).
Every power of 4 must be in the form of 1 followed by an even number of zeros (binary representation): 100...00:
100 = 4
10000 = 16
1000000 = 64
The 1st test ("if") is obvious.
When subtracting 1 from a number of the form XY100...00 you get XY011...11. So, the 2nd test checks whether there is more than one "1" bit in the number (XY in this example).
The last test checks whether this single "1" is in the correct position, i.e, bit #2,4,6 etc. If it is not, the masking (&) will return a nonzero result.
Below solution works for 2,4,16 power of checking.
public static boolean isPowerOf(int a, int b)
{
while(b!=0 && (a^b)!=0)
{
b = b << 1;
}
return (b!=0)?true:false;
}
isPowerOf(4,2) > true
isPowerOf(8,2) > true
isPowerOf(8,3) > false
isPowerOf(16,4) > true
var isPowerOfFour = function (n) {
let x = Math.log(n) / Math.log(4)
if (Number.isInteger(x)) {
return true;
}
else {
return false
}
};
isPowerOfFour(4) ->true
isPowerOfFour(1) ->true
isPowerOfFour(5) ->false