0

I want to do some bit operation in javascript on a variable. I have this numbers:

min: 153391689 (base 10) - 1111111111 (base 8) max: 1073741823 (base 10) - 7777777777 (base 8)

Now I want to use this variable for storing 10 "vars" with options from 0 to 7. For that, I need to get and set every octal digit (meaning 3 bits). Unfortunately, I didn't made it, but I came with something:

 var num = 153391689; function set(val, loc) { num |= val << (loc * 3); } function get(loc) { return (num & 7 << loc * 3) / Math.pow(8, loc); } 

Thank you.

2
  • 2
    your set never clears any bits. Commented Jul 22, 2015 at 15:35
  • Bitwise operations do only work on dual numbers. Commented Jul 23, 2015 at 2:02

1 Answer 1

2

As mentioned by Amit in a comment, your set function doesn't clear the bits before setting the value, so if there is already a value at that location then the new value will be ORed with it.

You can clear the location by ANDing the number with the bitwise NOT of the bitmask for that position. Applying a bitwise NOT to the mask means that only bits that are not in the location you are interested in remain set.

 function set(val, loc) { num &= ~(7 << (loc * 3)); // clear bits num |= val << (loc * 3); // set bits } 

Note that the brackets around the (loc * 3) are optional, because Javascript's order of operator precedence means that the multiplication will be done before the shift even without them.

Your get function looks like it will work, but you can simplify it. Instead of shifting the bitmask left, ANDing and then shifting right again (by doing a division), you can just shift right and then mask. This moves the bits you are interested in into the least significant 3 bits, and then masks them with the AND:

 function get(loc) { return (num >> (loc * 3)) & 7; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.