byte中bit解析

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值