java byte to bit

您所在的位置:网站首页 字节和比特之间的转换 java byte to bit

java byte to bit

2024-07-15 21:51| 来源: 网络整理| 查看: 265

java中,Byte和Bit之间的转换。一般用到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;

}

结束。

推荐您阅读更多有关于“ java转换bytebit字节 ”的文章



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3