The following Pseudo and JavaScript code is a extract from the implementation of a algorithm , i want to convert it to C++ .
Pseudo Code :
for b from 0 to 2|R| do
for i from 0 to |R| do
if BIT-AT(b, i) = 1 then // b’s bit at index i
JavaScript Code :
for (var b = 0; b < Math.pow(2, orders[r].length); b++) // use b's bits for directions
{
for (var i = 0; i < orders[r].length; i++)
{
if (((b >> i) & 1) == 1) { // is b's bit at index i on?
I don’t understand what is happening in the last line of this code , What Should be the C++ code for the above given JavaScript code . So far what i have written is :
for (int b = 0; b < pow(2, orders.at(r).size()); b++)
{
for (int i = 0; i < orders.at(r).size(); i++)
{
if (((b >> i) & 1) == 1)***//This line is not doing what it is supposed to do according to pseudo code***
The last line is giving me segmentation fault .
—
Edit:I apologize the problem was somewhere else , This code works fine .
After that the result is compared with the number 1.
So if, for example,
bis 8, andiis 2, it will do the following:00001000) by 2 bits to the right. The result will be00000100.00000100 BITWISE_AND 00000001, the result will be0.0 =/= 1, you will not enter that lastif.As for the logic behind this, the code
((b >> i) & 1) == 1)returnstrueif the bit numberiof thebvariable is1, andfalseotherwise.And I believe that c++ code will be the same, with the exception that we don’t have
Mathclass in c++, and you’ll have to replacevars with the corresponding types.