[英]Java Byte Array conversion Issue
我有一個字符串,其中包含一系列位(如“01100011”)和 while 循環中的一些整數。 例如:
while (true) {
int i = 100;
String str = Input Series of bits
// Convert i and str to byte array
}
現在我想要一個很好的最快的方法來將字符串和 int 轉換為字節數組。 到目前為止,我所做的是將int
轉換為String
,然后對兩個字符串應用getBytes()
方法。 但是,它有點慢。 有沒有其他方法可以(可能)比這更快?
轉換 int 很容易(小端):
byte[] a = new byte[4];
a[0] = (byte)i;
a[1] = (byte)(i >> 8);
a[2] = (byte)(i >> 16);
a[3] = (byte)(i >> 24);
轉換字符串,首先使用Integer.parseInt(s, 2)
轉換為 integer,然后執行上述操作。 如果您的位串可能高達 64 位,則使用Long
,如果它比這更大,則使用BigInteger
。
對於整數
public static final byte[] intToByteArray(int i) {
return new byte[] {
(byte)(i >>> 24),
(byte)(i >>> 16),
(byte)(i >>> 8),
(byte)i};
}
對於字符串
byte[] buf = intToByteArray(Integer.parseInt(str, 2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.