Byte和Bit之间的转换

// 返回无符号的2进制表示 1110011
String hex = Integer.toBinaryString(115);
System.out.println(hex);
// 返回2进制的字符串1110011对应的值 115
System.out.println(Integer.valueOf("1110011", 2));

// 16进制值转换成二进制
System.out.println(Long.parseLong("49", 16));
System.out.println(Long.parseLong("2F", 16));

 

/**
 * Byte转Bit
 */
public static String byteToBit(byte b) {
	return "" +(byte)((b >> 7) & 0x1) + 
	(byte)((b >> 6) & 0x1) + 
	(byte)((b >> 5) & 0x1) + 
	(byte)((b >> 4) & 0x1) + 
	(byte)((b >> 3) & 0x1) + 
	(byte)((b >> 2) & 0x1) + 
	(byte)((b >> 1) & 0x1) + 
	(byte)((b >> 0) & 0x1);
}

/**
 * Bit转Byte
 */
public static byte BitToByte(String byteStr) {
	int re, len;
	if (null == byteStr) {
		return 0;
	}
	len = byteStr.length();
	if (len != 4 && len != 8) {
		return 0;
	}
	if (len == 8) {// 8 bit处理
		if (byteStr.charAt(0) == '0') {// 正数
			re = Integer.parseInt(byteStr, 2);
		} else {// 负数
			re = Integer.parseInt(byteStr, 2) - 256;
		}
	} else {//4 bit处理
		re = Integer.parseInt(byteStr, 2);
	}
	return (byte) re;
}

 

自建博客地址:http://www.javacui.com/ ,内容与ITEYE同步!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值