在字节数组中的特定数目的字节中存储整数-JAVA

我正在尝试使用带槽的页面在Java中实现数据库,所以基本上我想要做的是将数据存储在特定数量的字节中。 所以这是我必须存储它的页面。

    protected byte[] myData = new byte[PAGE_SIZE*1024]; //array for storing my data

现在我想在myData的前4个字节中存储一个Integer,当我这样做时,如果Integer不超过255,则自动将其仅存储在一个字节中,但是我想使用的是4个字节整数是1还是10亿并不重要。

我的问题是,是否可以在Java中做到这一点?控制我的数据必须分配多少个字节,就像我将3分配给字节数组的前4个字节一样?

        if (recordFitsIntoPage(record)) {

            byte [] fix_rec = new byte [record.getFixedLength()];
            byte [] var_rec= new byte [record.getVariableLength()];

            var_rec = var_rec(record);
            fix_rec = fix_rec(record);

            byte  [] box = { (byte) record.getVariableLength(),(byte) offsetEnd };
            System.arraycopy(fix_rec,data,offset,record.getFixedLength());
            System.arraycopy(var_rec,offsetEnd,record.getVariableLength());
            read_bytes(data);
            this.numRecords++;
            }else {

                throw new  Exception("no more space left");

            }

我有一个固定大小的变量,需要将其存储在我的情况下,例如以12个字节存储,我一直在使用System.arraycopy(),但是在我的情况下这无关紧要,在我执行代码之后绑定异常“最后一个源索引12超出字节[9]的范围” 因为它只使用9个字节来存储我的数据,而不是12个。

suse119 回答:在字节数组中的特定数目的字节中存储整数-JAVA

method创建一个由32个字节组成的数组,该数组可以是给定的任何整数-1或10亿:

private static byte[] bigIntegerToBytes(BigInteger b,int numBytes) {
        byte[] src = b.toByteArray();
        byte[] dest = new byte[numBytes];
        boolean isFirstByteOnlyForSign = src[0] == 0;
        int length = isFirstByteOnlyForSign ? src.length - 1 : src.length;
        int srcPos = isFirstByteOnlyForSign ? 1 : 0;
        int destPos = numBytes - length;
        System.arraycopy(src,srcPos,dest,destPos,length);
        return dest;
    }

您准备存储array中的byte

    byte[] myData = new byte[PAGE_SIZE*1024];

您还亲自挑选了integer

    BigInteger myInteger = new BigInteger("50000000000");

然后我们将integer更改为32长度的byte[]

    byte[] bytesOfInteger = bigIntegerToBytes(myInteger,32);

最后,您将bytes中的前4个integer复制到您的byte[] myData

    System.arraycopy(bytesOfInteger,myData,3);

因此,这表明您可以将任何体面的大整数分配到固定的32 byte[]中。

本文链接:https://www.f2er.com/3123669.html

大家都在问