-3

Here, I have an array containing 0,1,-1's. I am replacing all -1's to 0's and then creating a String of 0's and 1's. Later, converting the string to Byte but by default, Byte.parseByte() converts the string to signed Byte. Please suggest to me a solution to convert it to an unsigned 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");
        } 
     }
}

Sample Output:

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
Jay Patel
  • 1,374
  • 1
  • 8
  • 17
  • Does this answer your question? [How to convert a binary representation of a string into byte in Java?](https://stackoverflow.com/questions/18600012/how-to-convert-a-binary-representation-of-a-string-into-byte-in-java) – Robert Harvey Jan 04 '21 at 22:13

1 Answers1

5

Converting a binary string of eight 0s and 1s to an unsigned byte is easy:

(byte) Integer.parseInt(string, 2);

No reason to use Byte.parseByte, since it won't accept the input.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413