問題描述
我需要將一對長度為 16 位的二進制序列存儲到一個字節數組(長度為 2)中.一個或兩個二進制數不會改變,因此進行轉換的函數可能是矯枉過正的.例如,16 位二進制序列是 1111000011110001.如何將其存儲在長度為 2 的字節數組中?
I need to store a couple binary sequences that are 16 bits in length into a byte array (of length 2). The one or two binary numbers don't change, so a function that does conversion might be overkill. Say for example the 16 bit binary sequence is 1111000011110001. How do I store that in a byte array of length two?
推薦答案
String val = "1111000011110001";
byte[] bval = new BigInteger(val, 2).toByteArray();
還有其他選擇,但我發現最好使用 BigInteger
類,它可以轉換為字節數組,來解決這類問題.我更喜歡 if,因為我可以從 String
實例化類,它可以表示各種基數,如 8、16 等,也可以這樣輸出.
There are other options, but I found it best to use BigInteger
class, that has conversion to byte array, for this kind of problems. I prefer if, because I can instantiate class from String
, that can represent various bases like 8, 16, etc. and also output it as such.
public static byte[] getRoger(String val) throws NumberFormatException,
NullPointerException {
byte[] result = new byte[2];
byte[] holder = new BigInteger(val, 2).toByteArray();
if (holder.length == 1) result[0] = holder[0];
else if (holder.length > 1) {
result[1] = holder[holder.length - 2];
result[0] = holder[holder.length - 1];
}
return result;
}
例子:
int bitarray = 12321;
String val = Integer.toString(bitarray, 2);
System.out.println(new StringBuilder().append(bitarray).append(':').append(val)
.append(':').append(Arrays.toString(getRoger(val))).append('
'));
這篇關于將二進制序列存儲在字節數組中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!