本文介紹了如何在Java中將字符串的二進制表示轉換為字節?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
正如標題所說,我該怎么做?它很容易從字符串 -> 字節 -> 字符串二進制轉換,但是我如何轉換回來?下面是一個例子.輸出是:'f' 到二進制:01100110294984
我在某處讀到可以使用 Integer.parseInt 但顯然不是這樣 :( 還是我做錯了什么?
謝謝,:)
公共類主{公共靜態無效主要(字符串[]參數){字符串 s = "f";字節[] 字節 = s.getBytes();StringBuilder 二進制 = new StringBuilder();對于(字節 b:字節){詮釋價值 = b;for (int i = 0; i <8; i++){binary.append((val & 128) == 0 ? 0 : 1);val <<= 1;}binary.append(' ');}System.out.println("'" + s + "' 轉二進制:" + binary);System.out.println(Integer.parseInt("01100110", 2));}}
解決方案
你可以使用Byte.parseByte()
基數為 2:
byte b = Byte.parseByte(str, 2);
<小時>
使用您的示例:
System.out.println(Byte.parseByte("01100110", 2));
<上一頁>102
as the title says, how do I do it? Its easy to convert from string -> byte -> string binary, But how do I convert back? Below is a example. The output is : 'f' to binary: 01100110 294984
I read somewhere that I could use the Integer.parseInt but clearly that is not the case :( Or am I doing something wrong?
Thanks, :)
public class main{
public static void main(String[] args) {
String s = "f";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
System.out.println(Integer.parseInt("01100110", 2));
}
}
解決方案
You can use Byte.parseByte()
with a radix of 2:
byte b = Byte.parseByte(str, 2);
Using your example:
System.out.println(Byte.parseByte("01100110", 2));
102
這篇關于如何在Java中將字符串的二進制表示轉換為字節?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!