JAVA位字符串轉byte

具體出處找不到了,記錄此方法在此處。

/**
 * 位字符串轉字節
 * @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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章