javascript - Bitwise operation on octal number -


i want bit operation in javascript on variable. have numbers:

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

now want use variable storing 10 "vars" options 0 7. that, need , set every octal digit (meaning 3 bits). unfortunately, didn't made it, came 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.

as mentioned amit in comment, set function doesn't clear bits before setting value, if there value @ location new value ored it.

you can clear location anding number bitwise not of bitmask position. applying bitwise not mask means bits not in location interested in remain set.

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

note brackets around (loc * 3) optional, because javascript's order of operator precedence means multiplication done before shift without them.

your get function looks work, can simplify it. instead of shifting bitmask left, anding , shifting right again (by doing division), can shift right , mask. moves bits interested in least significant 3 bits, , masks them and:

 function get(loc) {      return (num >> (loc * 3)) & 7;  } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -