Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Bitwise operations
- //All calculations will assume 32-bit numbers and take the required conversion steps
- //Original shifts/logic by Trung0246, modified by Choon
- //32-bit conversions
- function ConvTo32Bit (a) { //Signed conversion
- a = trunc(a%4294967296);
- if (a > 2147483647) {
- a -= 4294967296;
- } else if (a < -2147483648) {
- a += 4294967296;
- }
- return a;
- }
- function ConvTo32BitU (a) { //Unsigned conversion
- a = trunc(a%4294967296);
- if (a < 0) {
- a += 4294967296;
- }
- return a;
- }
- //Logic
- function NOT (a) { //~
- return -(ConvTo32Bit(a) + 1);
- }
- function OR (a, b) { //|
- a = ConvTo32Bit(a);
- b = ConvTo32Bit(b);
- let bit = 1;
- let resultReturn = 0;
- if (a < 0 || b < 0) {
- a -= -2147483648*(a < 0); //you could use += 2147483648, but this is for stylistic purposes
- b -= -2147483648*(b < 0);
- resultReturn = -2147483648;
- }
- while (a || b) {
- if (a%2 || b%2) {
- resultReturn += bit;
- }
- a = floor(a/2);
- b = floor(b/2);
- bit *= 2;
- }
- return resultReturn;
- }
- function AND (a, b) { //&
- a = ConvTo32Bit(a);
- b = ConvTo32Bit(b);
- let bit = 1;
- let resultReturn = 0;
- if (a < 0 && b < 0) {
- a -= -2147483648;
- b -= -2147483648;
- resultReturn = -2147483648;
- }
- while (a || b) {
- if (a%2 && b%2) {
- resultReturn += bit;
- }
- a = floor(a/2);
- b = floor(b/2);
- bit *= 2;
- }
- return resultReturn;
- }
- function XOR (a, b) { //^
- a = ConvTo32Bit(a);
- b = ConvTo32Bit(b);
- let bit = 1;
- let resultReturn = 0;
- if ((a < 0) != (b < 0)) {
- a -= -2147483648*(a < 0);
- b -= -2147483648*(b < 0);
- resultReturn = -2147483648;
- }
- while (a || b) {
- if (a%2 != b%2) {
- resultReturn += bit;
- }
- a = floor(a/2);
- b = floor(b/2);
- bit *= 2;
- }
- return resultReturn;
- }
- //Shifts
- function SHL (a, b) { //Bitwise Shift Left, <<
- a = ConvTo32BitU(a);
- b = b%32;
- if (b < 0) { return SHR(a, -b); } //Shirt Right instead
- ascent (i in 0..b) { a = ConvTo32BitU(a*2); } //ascent syntax will be useful for SAR
- return ConvTo32Bit(a);
- }
- function SHR (a, b) { //Bitwise Logical Shift Right, >>>
- a = ConvTo32BitU(a);
- b = b%32;
- if (b < 0) { return SHL(a, -b); } //Shift Left instead
- ascent (i in 0..b) { a = ConvTo32BitU(a/2); }
- return ConvTo32Bit(a);
- }
- function SAR (a, b) { //Bitwise Arithmetic Shift Right, >>
- a = ConvTo32BitU(a);
- b = b%32;
- let c = -2147483648*(a >= 2147483648);
- if (b < 0) { return SHL(a, -b); } //Shift Left instead
- ascent (i in 0..b) { a = ConvTo32BitU(a/2 + c); }
- return ConvTo32Bit(a);
- }
- //Rotations (for the crazy people)
- function ROL (a, b) { //Bitwise Rotation Left
- return OR(SHR(a, 32 - b), SHL(a, b));
- }
- function ROR (a, b) { //Bitwise Rotation Right
- return OR(SHR(a, b), SHL(a, 32 - b));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement