Store binary sequence in byte array?

前端 未结 2 1153
无人及你
无人及你 2020-12-17 06:50

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 co

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 07:27

        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'));
    

提交回复
热议问题