在java方法中,将整数作为参数传递,并将整数解释为位

在java方法中,将整数作为参数传递,并将整数解释为位,java,bit-manipulation,Java,Bit Manipulation,我想写一个方法,其中方法的参数是int,可能的值是1-8。 在这个方法中,我有4个布尔值,它们的值必须设置为整数对应的位值 method(int x){ bool1 = value at the first bit, 0 = false, 1 = true; bool2 = value at the second bit, 0 = false, 1 = true; bool3 = value at the third bit, 0 = false, 1 = true; b

我想写一个方法,其中方法的参数是int,可能的值是1-8。 在这个方法中,我有4个布尔值,它们的值必须设置为整数对应的位值

method(int x){
   bool1 = value at the first bit, 0 = false, 1 = true;
   bool2 = value at the second bit, 0 = false, 1 = true;
   bool3 = value at the third bit, 0 = false, 1 = true;
   bool4 = value at the last bit, 0 = false, 1 = true;
}
因此,如果必须设置bool1=false,bool2=true,bool3=false,bool4=true, 我会将5作为参数传递给转换为二进制0101的方法

我不知道如何在Java语法和最佳代码方面做到这一点


提前谢谢。不是作业

您可以使用掩码和按位and运算符检查是否设置了每个位

//0x8 is 1000 in binary, if the correctbit is set in x then x & 0x8 will
//equal 0x8, otherwise it will be 0.
bool1 = (0x8 & x) != 0;
//Do the same for the other bits, with the correct masks.
bool2 = (0x4 & x) != 0;
bool3 = (0x2 & x) != 0;
bool4 = (0x1 & x) != 0;

您的规格转换为:

void method(int x) {
   boolean bool1 = (x & 8) > 0;
   boolean bool2 = (x & 4) > 0;
   boolean bool3 = (x & 2) > 0;
   boolean bool4 = (x & 1) > 0;
}

你说的第一点是什么意思?最重要还是最不重要?Java位运算符的第一个Google结果:最重要,我的意思是5=0101=false,true,false,true..所以您需要0001到1000的值。因此,只有当值为8时才会设置第一位。我不知道的是如何设置布尔值。我想下面的两个答案解决了我的问题。