开发者

How to find the value of a byte in a large integer efficiently

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.


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]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜