我正在为Dart创建一个加密包(crypt)。现在,我所做的大部分工作都是从PointyCastle或简单的ish算法中暴露出来的,在这些算法中,按位旋转是不必要的,或者是由>>和<<代替的。
然而,当我转向复杂的密码解决方案时,我不能确定如何以最大的效率在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没有无符号的右移位或左移位,这意味着>>和<<是有符号的右移位,这比我想象的更有意义。它提出了一个挑战,其他语言并没有在设计一个答案。下面被接受的答案解释了这一点,并说明了按位旋转的正确方法。
发布于 2019-08-20 09:43:47
正如所指出的,Dart没有>>> (无符号右移位)操作符,所以您必须依赖有符号的shift操作符。
在这种情况下,
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位数进行.
https://stackoverflow.com/questions/57565112
复制相似问题