。
package test.jni;
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Byte.SIZE);
byte b = 127; // 127的二进制是0111 1111
System.out.println(b);
System.out.println(Arrays.toString(getBooleanArray(b)));
// 0111 1111对应127
boolean[] array = new boolean[] { false, true, true, true, true, true,
true, true };
System.out.println(getByte(array));
}
/**
* 将byte转换为一个长度为8的boolean数组(每bit代表一个boolean值)
*
* @param b
* byte
* @return boolean数组
*/
public static boolean[] getBooleanArray(byte b) {
boolean[] array = new boolean[8];
for (int i = 7; i >= 0; i--) { // 对于byte的每bit进行判定
array[i] = (b & 1) == 1; // 判定byte的最后一位是否为1,若为1,则是true;否则是false
b = (byte) (b >> 1); // 将byte右移一位
}
return array;
}
/**
* 将一个长度为8的boolean数组(每bit代表一个boolean值)转换为byte 2014-7-4 下午5:28:28
*
* @param array
* @return
*
*/
public static byte getByte(boolean[] array) {
if (array != null && array.length > 0) {
byte b = 0;
for (int i = 0; i <= 7; i++) {
if (array[i]) {
int nn = (1 << (7 - i));
b += nn;
}
}
return b;
}
return 0;
}
}
打印
8
127
[false, true, true, true, true, true, true, true]
127
。