【问题标题】:How to convert string of 0s and 1s to unsigned Byte? [closed]如何将 0 和 1 的字符串转换为无符号字节? [关闭]
【发布时间】:2021-01-05 06:14:14
【问题描述】:

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

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");
        } 
     }
}

样本输出:

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

【问题讨论】:

标签: java byte


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2018-05-02
    相关资源
    最近更新 更多