存储在字节数组二进制序列? [英] Store binary sequence in byte array?
问题描述
我需要存储的长度为16位转换成字节数组(长度为2)一对夫妇的二进制序列。一个或两个二进制数没有改变,这样做转换的函数可能是矫枉过正。例如说16位二进制序列是1111000011110001.如何存放在长度为2的字节数组?
字符串VAL =1111000011110001;
字节[] = BVAL新的BigInteger(VAL,2).toByteArray();
有其他的选择,但我发现它最好使用的BigInteger
类,具有转换为字节数组,因为这样那样的问题。我preFER如果,因为我可以从字符串
实例类,可以重新present各种碱如8,16等,也输出它是这样。
编辑:周一...:P
公共静态的byte [] getRoger(字符串VAL)抛出NumberFormatException异常,
空指针异常 {
字节[]结果=新的字节[2];
字节[] =持有新的BigInteger(VAL,2).toByteArray(); 如果(holder.length == 1)导致[0] =支架[0];
否则如果(holder.length→1){
结果[1] =支架[holder.length - 2];
结果[0] =支架[holder.length - 1];
}
返回结果;
}
例如:
INT bitarray = 12321;
串VAL = Integer.toString(bitarray,2);
。的System.out.println(新的StringBuilder()追加(bitarray).append(':')追加(VAL)
。.append(':')追加(Arrays.toString(getRoger(VAL)))追加('\\ n'));
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();
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.
Edit: Mondays ... :P
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;
}
Example:
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('\n'));
这篇关于存储在字节数组二进制序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!