【发布时间】:2014-06-17 21:16:47
【问题描述】:
我正在尝试根据b / n 的小数部分移动字节数组
我使用的(简化的)公式是(给定n = 2):
b = b / 2
if (decimal part of b == 0.5) {
b = floor(b) + 256 / 2
}
所以在这种情况下:
b = 0 then 0
b = 1 then 128
b = 2 then 2
b = 3 then 129
在我到达 n = 6 之前它工作正常,但我不确定如何修复它。
这是一个完整的例子:http://jsfiddle.net/cBY2H/4/embedded/result,js/
可以在控制台输出中看到:
Shift by 2-5: fine
Shift by 6:
Extra 128
Missing 213
Shift by 7:
Extra 110
Missing 219
Shift by 8: fine
我怎样才能使它至少适用于n = 2-9,甚至更好的n = 2+?
执行转换的实际代码:
function shiftByte(byte, shiftAmount) {
var shiftSize = 256 / shiftAmount,
decimal = 1 / shiftAmount,
currentDecimal = decimal,
shiftCount = 1;
byte = byte / shiftAmount;
while (numberLessThan(currentDecimal, 1)) {
if (numberEquals(byte - Math.floor(byte), currentDecimal)) {
return Math.ceil(shiftSize * shiftCount) + Math.floor(byte);
}
currentDecimal += decimal;
shiftCount++;
}
return Math.floor(byte);
}
【问题讨论】:
-
可能由于十进制分辨率,您的 numberEquals() 函数有时会返回 false。
-
@AbhishekBansal
numberEquals与==差不多,但有一个0.000001容差来满足浮点精度。该函数的来源在 JS Fiddle:(a + tolerance) >= b && (a - tolerance) <= b。 -
这是错字吗:
b = 2 then 2?我希望是 1,否则我不理解这个例子。
标签: javascript algorithm binary