Java:将 bool 数组转换为单个 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11526582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Convert bool array into a single int
提问by asboans
I have a boolean array (length = 2) that I want to consecrate and convert to an integer so that individual bits inside the integer would represent values from the boolean array:
我有一个布尔数组(长度 = 2),我想将其转换为整数,以便整数中的各个位代表布尔数组中的值:
[false, false] = 0
[false, true] = 1
[true, false] = 2
[true, true] = 3
回答by Alnitak
This will work:
这将起作用:
int n = (a[0] ? 2 : 0) + (a[1] ? 1 : 0);
If you want a more general solution:
如果您想要更通用的解决方案:
int n = 0, l = a.length;
for (int i = 0; i < l; ++i) {
n = (n << 1) + (a[i] ? 1 : 0);
}
回答by gustafc
Generic way for any-length array (although only the last 32 elements make a difference, since ints are 32 bits):
任意长度数组的通用方法(尽管只有最后 32 个元素有所不同,因为整数是 32 位):
int booleansToInt(boolean[] arr){
int n = 0;
for (boolean b : arr)
n = (n << 1) | (b ? 1 : 0);
return n;
}
回答by assylias
int i = (array[0] ? 2 : 0) + (array[1] ? 1 : 0);
General solution for length != 2:
长度 != 2 的通用解决方案:
public static void main(String[] args) {
boolean[] array = {true, true, false};
int number = 0;
int j = array.length - 1;
for (int i = 0; i < array.length; i++) {
if (array[i])
number += 1 << j--;
}
}
回答by BlackVegetable
int number = 0;
for(int i = array.length - 1; i >= 0; i--)
{
if(array[i])
{
int exponent = (array.length - 1 - i)
number += Math.pow( 2, exponent );
}
}