Java将8位数字转换为10位数字

Java将8位数字转换为10位数字,java,bit-manipulation,bytebuffer,bitset,Java,Bit Manipulation,Bytebuffer,Bitset,我从字节缓冲存储器中读取数据,但我需要的值存储为10位。即: 1100101110 = 814 使用数字序列的示例: 8 bit 10 bit 01 02 03 04 05 06 07 08 | 09 10 | 11 12 13 14 15 16 最终将是: 8 bit 10 bit 08 07 06 05 04 03 02 01 | 16 15 | 14 13 12 11 10 09 因此,我可

我从
字节缓冲存储器中读取数据,但我需要的值存储为10位。即:

1100101110 = 814 使用数字序列的示例:

                     8 bit    10 bit
01 02 03 04 05 06 07 08 | 09 10 | 11 12 13 14 15 16
最终将是:

                     8 bit    10 bit
08 07 06 05 04 03 02 01 | 16 15 | 14 13 12 11 10 09
因此,我可以管理第一个字节的任意顺序,但最后两位取自下一个字节的错误端

我目前的代码如下:

// bb stands for the ByteBuffer in use.
//length stands for the number bytes covering the 10 bit numbers
BitSet data = getBitSet(bb, length);
int totalNumbers = data.length() / 10;
int[] numbers = new int[totalNumbers];
for (int i=0; i < totalNumbers; i++){
    int start = i*10;
    int end = (i+1)*10;
    BitSet bs = data.get(start, end);
    int tenBitNumber = 0;
    for (int j = bs.nextSetBit(0); j >= 0; j = bs.nextSetBit(j+1)) {
        double power = pow(2, 9-j);
        tenBitNumber += power;
    }
    numbers[i] = tenBitNumber;
}

最好的解决方案是什么?我需要从ByteBuffer中读取多个10位长度的数字。首先,让我们处理一种情况,即有5个字节(40位,或4个10位数字)可用:将输入分成5个字节的块。每个区块将产生一组四个10位数字:

int[] convertFive(byte a, byte b, byte c, byte d, byte e) {
    int p = ((a & 0xff) << 2) | (b & 0xc0) >>> 6;
    int q = ((b & 0x3f) << 4) | (c & 0xf0) >>> 4;
    int r = ((c & 0x0f) << 6) | (d & 0xfc) >>> 2;
    int s = ((d & 0x03) << 8) | (e & 0xff) >>> 0;
    return new int [] { p, q, r, s }; 
}
int[]convertFive(字节a、字节b、字节c、字节d、字节e){
int p=((a&0xff)>>6;
intq=((b&0x3f)>>4;
int r=((c&0x0f)>>2;
ints=((d&0x03)>>0;
返回新的int[]{p,q,r,s};
}
将这四个
int
s追加到输出以生成最终结果。您可以修改该方法以在执行时追加输出,而不是一直创建四元素数组


以类似的方式处理剩余的小于5字节的数据块:两个字节变成一个10位的数字,三个字节变成两个数字,四个字节变成三个数字。如果剩余的长度是一个字节,则输入无效。

典型的解决方案是在
int
中缓冲位,从中提取10个片段并附加一个新的必要时使用字节。不是这种奇怪的逐位浮点数据,它是模糊且缓慢的。第一个示例中的
10
来自哪里?是下一个字节的MSB吗?如果答案是?是的“,那么下面的6位呢?假设您有一个字节序列
aaaaaa bbbbbbbb ccccccccccccccccccccccccdddd eeeeeeee
。是否需要将其重新分区为
aaaaaaaa bbbbbb ccccccccccccccccdddd eeeeee
?@dasblinkenlight是的,但我认为harold在我想做的事情的右边。谢谢您的帮助!”) 11001011|10110111|00101100|11000111 11010011|11101101|00110100|11100011
int[] convertFive(byte a, byte b, byte c, byte d, byte e) {
    int p = ((a & 0xff) << 2) | (b & 0xc0) >>> 6;
    int q = ((b & 0x3f) << 4) | (c & 0xf0) >>> 4;
    int r = ((c & 0x0f) << 6) | (d & 0xfc) >>> 2;
    int s = ((d & 0x03) << 8) | (e & 0xff) >>> 0;
    return new int [] { p, q, r, s }; 
}