如何将0和1的字符串转换为无符号字节?

Jay*_*tel -3 java byte

这里,我有一个包含 0,1,-1 的数组。我将所有 -1 替换为 0,然后创建一个由 0 和 1 组成的字符串。稍后,将字符串转换为 Byte,但默认情况下,Byte.parseByte() 会将字符串转换为带符号的 Byte。请向我建议一个将其转换为无符号字节的解决方案。

public class Test{

     public static void main(String []args){
        int[][] intArray = new int[][]{ 
            {-1,0,0,-1,0,1,1,0},
            {1,1,0,-1,0,0,-1,0},
            {-1,0,1,1,0,-1,1,0},
            {1,-1,-1,0,0,1,-1,0}
        }; 
        
        
        for(int j=0; j<intArray.length;j++){
            String BitString = "";
            for(int i=0; i<8;i++ ){
                if (intArray[j][i] == -1){
                    BitString = BitString + "0";
                }
                else{
                    BitString = BitString + intArray[j][i];
                }
            }
            System.out.println(BitString);
            
            try{
                Byte b = Byte.parseByte(BitString,2);
                System.out.println(b);
                System.out.println(b.getClass().getName());
            }
            catch(Exception e){
                System.out.println(e.toString());
            }
            System.out.println("\n");
        } 
     }
}
Run Code Online (Sandbox Code Playgroud)

示例输出:

00000110
6
java.lang.Byte


11000000
java.lang.NumberFormatException: Value out of range. Value:"11000000" Radix:2


00110010
50
java.lang.Byte


10000100
java.lang.NumberFormatException: Value out of range. Value:"10000100" Radix:2
Run Code Online (Sandbox Code Playgroud)

Lou*_*man 5

将八个 0 和 1 的二进制字符串转换为无符号字节很容易:

(byte) Integer.parseInt(string, 2);
Run Code Online (Sandbox Code Playgroud)

没有理由使用Byte.parseByte,因为它不接受输入。