如何高效地找到一个大整数中的一个字节的值

发布于 2024-10-26 07:56:56 字数 367 浏览 1 评论 0原文

我想找到一个大整数中一个字节的值。例如

11973777 = 10110110 10110100 10010001

我想找到的

11973777[2] = 10110110 = 182
11973777[1] = 10110100 = 180 
11973777[0] = 10010001 = 145

数字并且有效地做到这一点(按位运算)。我可以通过按位运算轻松找到数字中任何位置的位值,但我不想仅仅为了获取字节而执行 8 次,或者先左移然后右移。这被标记为 javascript,因为我正在 javascript 中执行此操作,但我认为可以翻译按位运算。预先感谢您提供的任何帮助。

I want to find the value of a byte in a large integer. For example the number

11973777 = 10110110 10110100 10010001

I would like to find that

11973777[2] = 10110110 = 182
11973777[1] = 10110100 = 180 
11973777[0] = 10010001 = 145

And do so efficiently(bitwise operations). I can easily find the value of a bit at any position in the number with a bitwise operation but I don't want to do that 8 times just to get the byte, or shift left then shift right. This is tagged as javascript because I am doing it in javascript but I suppose bitwise operations can be translated. Thank you in advance for any help you can lend.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

漆黑的白昼 2024-11-02 07:56:56

在某种程度上,你必须进行位移:

var num = 11973777;
var lastByte = num & 0xFF;
var midLowByte = (num >> 8) & 0xFF;
var midHighByte = (num >> 16) & 0xFF;
var highByte = (num >> 24) & 0xFF;

但你总是可以将逻辑封装在函数中以使其更方便,例如:

window.getBytes = function(num) {
    return [num & 0xFF, (num >> 8) & 0xFF, (num >> 16) & 0xFF, (num >> 24) & 0xFF];
};

var numBytes = getBytes(11973777);
alert(numBytes[0] + "," + numBytes[1] + "," + numBytes[2] + "," + numBytes[3]);

To a certain extent, you have to bit-shift:

var num = 11973777;
var lastByte = num & 0xFF;
var midLowByte = (num >> 8) & 0xFF;
var midHighByte = (num >> 16) & 0xFF;
var highByte = (num >> 24) & 0xFF;

But you can always package the logic in a function to make it more convenient, like:

window.getBytes = function(num) {
    return [num & 0xFF, (num >> 8) & 0xFF, (num >> 16) & 0xFF, (num >> 24) & 0xFF];
};

var numBytes = getBytes(11973777);
alert(numBytes[0] + "," + numBytes[1] + "," + numBytes[2] + "," + numBytes[3]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文