byte中bit解析

来源:互联网 发布:中国移动优化工作 编辑:程序博客网 时间:2024/06/03 13:04

package test.jni;import java.util.Arrays;public class Test {public static void main(String[] args) {// TODO Auto-generated method stubSystem.out.println(Byte.SIZE);byte b = 127; // 127的二进制是0111 1111System.out.println(b);System.out.println(Arrays.toString(getBooleanArray(b)));// 0111 1111对应127boolean[] 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;否则是falseb = (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



0 0
原创粉丝点击