1
public static byte[][] keyArray = new byte[4][4]; 
String hex = "93";
String hexInBinary = Integer.toBinaryString(Integer.parseInt(hex, 16));
keyArray[row][col] = Byte.parseByte(hexInBinary,2); //this line causes the error

これは私が得るエラーメッセージです、

"Exception in thread "main" java.lang.NumberFormatException: Value out of range. Value:"10010011" Radix:2."

実際には「0A935D11496532BC1004865ABDCA42950」という長い文字列があるため、getBytes() を使用したくありません。一度に2つの16進数を読み取り、バイトに変換したい。

編集:

どのように修正したか:

String hexInBinary = String.format("%8s", Integer.toBinaryString(Integer.parseInt(hex, 16))).replace(' ', '0');
keyArray[row][col] = (byte)Integer.parseInt(hexInBinary, 2);
4

3 に答える 3

1
public class ByteConvert {
    public static void main(String[] argv) {
        String hex = "93";
        String hexInBinary = Integer.toBinaryString(Integer.parseInt(hex, 16));
        int intResult = Integer.parseInt(hexInBinary,2);
        System.out.println("intResult = " + intResult);
        byte byteResult = (byte) (Integer.parseInt(hexInBinary,2));
        System.out.println("byteResult = " + byteResult);
        byte result = Byte.parseByte(hexInBinary,2);
        System.out.println("result = " + result);
    }
}

C:\JavaTools>java ByteConvert
intResult = 147
byteResult = -109
Exception in thread "main" java.lang.NumberFormatException: Value out of range.
Value:"10010011" Radix:2
        at java.lang.Byte.parseByte(Unknown Source)
        at ByteConvert.main(ByteConvert.java:9)

ご覧のとおり、 parseByte は よりも「大きい」値を検出しますbyte

于 2013-10-30T00:34:24.423 に答える