0

So I am working on a solution where I need any given data type to be broken into a 13 bit encoding I am able to work with everything else except string.

So Steps as I look to code this.

Convert String to byte array

Collect first byte in a short with bit shift of byte to 13

Bit shift next byte with 5 and or it with short to get first short

This is getting cumbersome to iterate I think the approach is all wrong. Can I get a possible solution?

4

3 回答 3

2

使用BigInteger. 用byte[]. 虽然它不是零,但使用该方法屏蔽掉 13 位and()并转换为短 via intValue()。将其向右移动 13 位shiftRight()并重复。

于 2013-01-09T00:06:58.470 回答
1

OpenLR在此处提供了一个二进制库

它有一个在其构造函数ByteArrayBitstreamInput中接受byte[]参数的类,然后您可以获取任意数量的位getInt()并将其转换为short.

于 2013-01-09T00:05:55.613 回答
1

此代码经过轻微测试。这是一个低级别的解决方案,但不会有太多开销(比如移动整个输入或垃圾生成或库膨胀)。

// Length of shorts array must be at least (8 * bytes.length + 12) / 13.
static void convert(byte[] bytes, short[] shorts) {
    int nBitsAvail = 13;
    int i = 0;
    for (byte b : bytes) {
        if (nBitsAvail >= 8) {
            // Entire byte fits in available space in short.
            shorts[i] = (short) ((shorts[i] << 8) | b);
            nBitsAvail -= 8;
        } else {
            // Byte must be split between bits remaining in this short and the next.
            int nBitsNeeded = 8 - nBitsAvail ;
            shorts[i] = (short) ((shorts[i] << nBitsAvail) | (b >> nBitsNeeded));
            shorts[++i] = (short) (b & (0xff >> nBitsAvail));
            nBitsAvail = 13 - nBitsNeeded;
        }
    }
    shorts[i] <<= nBitsAvail;
}
于 2013-01-09T00:07:06.613 回答