如何在 dart 中创建按位旋转函数?

How would one create a bitwise rotation function in dart?

我正在为 Dart (https://pub.dev/packages/steel_crypt) 创建一个加密包。现在,我所做的大部分工作要么是从 PointyCastle 公开的,要么是简单的算法,在这些算法中,按位旋转是不必要的,或者可以用 >> 和 << 代替。

但是,当我转向复杂的密码学解决方案(我可以用数学方法解决)时,我不确定如何在 Dart 中以最大效率实现按位旋转。由于密码学的性质,速度部分被强调并且毫不妥协,因为我需要绝对最快的实现。

我从Java移植了一种按位旋转的方法。我很确定这是正确的,但不确定效率和可读性:

我测试过的实现如下:


int INT_BITS = 64; //Dart ints are 64 bit

static int leftRotate(int n, int d) { 

    //In n<<d, last d bits are 0.  
    //To put first 3 bits of n at 
    //last, do bitwise-or of n<<d with 
    //n >> (INT_BITS - d)

    return (n << d) | (n >> (INT_BITS - d)); 
} 

static int rightRotate(int n, int d) { 

    //In n>>d, first d bits are 0.  
    //To put last 3 bits of n at 
    //first, we do bitwise-or of n>>d with 
    //n << (INT_BITS - d)

    return (n >> d) | (n << (INT_BITS - d)); 
}

编辑(为清楚起见):Dart 没有无符号右移或左移,这意味着 >> 和 << 是 有符号 右移,这比我可能具有的意义更大想法。它提出了其他语言在设计答案方面没有的挑战。下面接受的答案对此进行了解释,还显示了按位旋转的正确方法。

如前所述,Dart 没有 >>>(无符号右移)运算符,因此您必须依赖有符号移位运算符。

在那种情况下,

int rotateLeft(int n, int count) {
  const bitCount = 64; // make it 32 for JavaScript compilation.
  assert(count >= 0 && count < bitCount);
  if (count == 0) return n;
  return (n << count) | 
      ((n >= 0) ? n >> (bitCount - count) : ~(~n >> (bitCount - count)));
}

应该可以。

此代码仅适用于本机 VM。当编译为 JavaScript 时,数字是双精度数,并且仅对 32 位数字进行按位运算。