将二进制序列存储在字节数组中?

2022-01-09 00:00:00 binary java

我需要将一对长度为 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('
'));

相关文章