简体   繁体   中英

JavaScript Bit Manipulation to C++ Bit Manipulation

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 .

(((b >> i) & 1) == 1)
     |     |
     |     |
     |    bitwise AND between the result of the shift and number 1.
     |
    shift b by i bits to the right

After that the result is compared with the number 1.

So if, for example, b is 8, and i is 2, it will do the following:

  1. shift 8 (which is 00001000 ) by 2 bits to the right. The result will be 00000100 .
  2. apply the bitwise AND: 00000100 BITWISE_AND 00000001 , the result will be 0 .
  3. Compare it with 1. Since 0 =/= 1 , you will not enter that last if .

As for the logic behind this, the code ((b >> i) & 1) == 1) returns true if the bit number i of the b variable is 1 , and false otherwise.

And I believe that c++ code will be the same, with the exception that we don't have Math class in c++, and you'll have to replace var s with the corresponding types.

>> is the right shift operator, ie take the left operand and move its bit n positions to the right (defined by the right operand).

So essentially, 1 << 5 would move 1 to 100000 .

In your example (b >> i) & 1 == 1 will check whether the i-th bit is set (1) due to the logical and ( & ).

As for your code, you can use it (almost) directly in C or C++. Math.pow() would become pow() inside math.h , but (in this case) you could simply use the left shift operator:

for (int b = 0; b < (1 << orders[r].length); ++b) // added the brackets to make it easier to read
    for (int i = 0; i < orders[r].length; ++i)
        if (((b >> i) & 1) == 1) {
            // ...
        }

1 << orders[r].length will essentially be the same as pow(2, orders[r].length) , but without any function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM