Search code examples
bit-manipulationbitwise-operatorsjsonata

JSONata bit-manipulation


Is it possible to do somehow bit manipulation on integers in JSONata?

& is concatenation operator, and I didn't find anything about bit manipulation in docs(shifting, bitwise logical operation) I would like to achieve C-type manipulation somehow. e.g.: a=0x10 & 0xEF where a should be 0x00 after evaluation.


Solution

  • As far as I'm aware, there are no "out of the box" bit manipulation functions available in JSONata, but you can extend JSONata by providing your own. For example:

    Excerpt from Github Discussion about random values/UUIDs:

    (
      $binPad:=function($n, $len){$pad($formatBase($n,2),-$len,'0')};
      $bitwise:=function($lb, $rb, $fn){$split($lb,'')~>$map(function($c, $i){$fn($c='1',$substring($rb,$i,1)='1')?$power(2,(7-$i)):0})~>$sum()};
      $and:=function($l,$r){$bitwise($binPad($l,8),$binPad($r,8),function($1,$2){$1 and $2})};
      $or:=function($l,$r){$bitwise($binPad($l,8),$binPad($r,8),function($1,$2){$1 or $2})};
    
      ...
    
    )
    

    Full disclosure: I did not write these functions, but I had seen this used in other scenarios and I am merely suggesting this as an option to the OP.