how to replicate javascript bit-shift, bit-wise operations in java,

删除回忆录丶 提交于 2021-01-27 20:54:23

问题


I am trying to replicate the behavior of javascript bit-shift and bit-wise operations in java.

Did you ever try to do this before, and how can you do it reliably and consistently even with longs?

  var i=[some array with large integers];
  for(var x=0;x<100;x++)
  {
    var a=a large integer;

    var z=some 'long'>2.1 billion;
    //EDIT:
    z=i[x]+=(z>>>5)^(a<<2))+((z<<4)^(a<<5));

  }

what would you do to put this into java?


回答1:


Yes. Java has bit-wise operators and shift operators.

Is there something in particular you wish to ask?

edit: Ah, just cast to an int before shifting.

int zz = ((int) 123456789123L) << 20;

You will get -1473249280 just as you note the JavaScript gives you.

edit2: Do you just want something like this?

   long[] i=[some array with large integers];
   for(int x=0; x < 100; x++)
   {
     int a= (int) <a large integer>; // cast in case it's a long or something
     long z= <some 'long' gt 2.1 billion>;
     z=i[x]+=((int) z)>>>5)^(a<<2));
   }



回答2:


Java has bitwise operators that behave by-and-large the same. There is a subtle difference though.

Java's int type is 32-bit signed, whereas JavaScript's >>> operator returns a 32-bit unsigned integer value, so the following

"" + ((1 << 31) >>> 0)

produces

"2147483648"

in JavaScript but the same expression produces

"-2147483648"

in Java.

Java's long type will let you get all the precision you need to replicate JavaScript bit manipulation but you need to be sure to mask it to 32 signed bits when using >>> where the shift amount might be 0 (or a multiple of 32).

You can get the 32 low bits of a long by doing

(myLong & 0xffffffffL)



回答3:


one way to translate bitshift and addition operations from javascript to java is to isolate the operands of a bit shift operation with int casts, and isolate operands of an addition/subtraction operation with long casts (since java will cast an addition operation exceeding 2 bil to an int without them, and javascript automatically casts longs in bitshifts to ints, while java doesn't:

       long z=(long)(((int)z>>>5)^((int)a<<2))+(long)(((int)z<<4)^((int)a<<5)); 


来源:https://stackoverflow.com/questions/8515274/how-to-replicate-javascript-bit-shift-bit-wise-operations-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!