如何通过移位将多个小整数保存在一个整数中? [英] How do I save multiple small integers in one integer via bitshifting?
问题描述
我在int[][][]
数组中工作,我需要从静态函数返回该数组一个字段的地址.
考虑到数组的维数将保持较小(int[32][32][32]
)的事实,我想到了返回一个包含所有三个值的数字,而不是使用包含三个数字的数组.
I am working in an int[][][]
array and I need to return an address of one field of that array from a static function.
Given the fact that the dimensions of the Array will stay small (int[32][32][32]
) I had the idea to return one number containing all three Values, instead of using an Array containing the three numbers.
我已经有了一个可行的解决方案,我将我的电话号码打包成一个字符串,然后通过Integer.parseInt(String)
在接收方法中将其解压缩.
不幸的是,这在运行时方面效果不佳,所以我想到了移位.
I already had a working solution, where i packed my number into a String and unpacked it in the receiving method via Integer.parseInt(String)
.
Unfortunately this didn't work quite, well in terms of runtime, so i thought of bitshifting.
对于我的英语不好,我深表歉意,希望这个简单的问题值得您珍惜:)
I apologize for my bad english and hope this simple question is worth your time :)
推荐答案
如果您的数字在0 ... 255范围内,此示例会将三个数字编码为一个int,然后再次对其进行解码...
If your numbers are in the range 0...255, this example will encode three numbers into one int and then decode it again...
public class BitDemo {
public static void main(String[] args) {
int encoded = encode(20, 255, 10);
int[] decoded = decode(encoded);
System.out.println(Arrays.toString(decoded));
}
private static int[] decode(int encoded) {
return new int[] {
encoded & 0xFF,
(encoded >> 8) & 0xFF,
(encoded >> 16) & 0xFF
};
}
private static int encode(int b1, int b2, int b3) {
return (b1 & 0xFF) | ((b2 & 0xFF) << 8) | ((b3 & 0xFF) << 16);
}
}
(b1 & 0xFF)
-获取b1的前8位
((b2 & 0xFF) << 8)
-获取b2的前8位并将其左移8位
((b2 & 0xFF) << 8)
- Gets the first 8 bits of b2 and shifts them left 8 bits
((b3 & 0xFF) << 16)
-获取b3的前8位并将其左移16位
((b3 & 0xFF) << 16)
- Gets the first 8 bits of b3 and shifts them left 16 bits
这三个数字相加或.
如果您使用负数或大于255的数字,则会得到不同的结果.
If you have negative numbers or number more than 255, you'll get different results.
这篇关于如何通过移位将多个小整数保存在一个整数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!