当前位置: 代码迷 >> 综合 >> JAVA位字符串转byte
  详细解决方案

JAVA位字符串转byte

热度:12   发布时间:2023-10-25 14:12:11.0

具体出处找不到了,记录此方法在此处。

/*** 位字符串转字节* @param str 位字符串,如00000001* @return byte转换结果,如1*/
public static byte bitStringToByte(String str) {if(null == str){throw new RuntimeException("when bit string convert to byte, Object can not be null!");}if (8 != str.length()){throw new RuntimeException("bit string'length must be 8");}try{//判断最高位,决定正负if(str.charAt(0) == '0'){return (byte) Integer.parseInt(str,2);}else if(str.charAt(0) == '1'){return (byte) (Integer.parseInt(str,2) - 256);}}catch (NumberFormatException e){throw new RuntimeException("bit string convert to byte failed, byte String must only include 0 and 1!");}return 0;
}