2015-08-25 14 views
1

奇怪的問題,但我提供的框架包含一個哈希表,其中返回值是字符串。字符串代表我需要處理的二進制值。例如,我輸入「F」鍵,它將返回一個0和1的字符串,如「10011」。我需要使用該數字10011作爲二進制文件,並最終將其存儲爲二進制文件。我如何將「10011」轉換爲00010011字節?將存儲爲字符串(「10011」)的二進制值轉換爲Java中的字節表示形式(0b00010011)?

+0

你的意思'(字節)的Integer.parseInt(字符串,2);'? –

+2

或'Byte.parseByte(string,2)'? –

+0

你想要一個字符串「」0b00010011「」或「int」或「字節」? – durron597

回答

2

您可以使用Integer.parseInt(String str, int radix),radix爲2表示二進制,8表示八進制,10表示十進制,16表示十六進制。

int number = Integer.parseInt(binaryString, 2); 
// Or use this if you prefer using byte 
byte number = Byte.parseByte(binaryString, 2); 
+0

爲什麼downvote? – leonbloy

+0

不,用戶有一個字符串,他想要一個字節 – leonbloy

+0

當然,這個假定二進制值適合一個字節。 – leonbloy

0

你可以嘗試使用Integer類的this方法。基數是計數系統的基礎。

0

Integer.parseInt(input, 2)例如:

class ToBinary { 
    public static void main(String ... args) { 
     String input = "10011"; 
     byte output = (byte) Integer.parseInt(input, 2); 
     System.out.println(output); 
    } 
} 
相關問題