ishak lahlouh
ishak lahlouh

Reputation: 65

storing an integer in a specific number of bytes in an array of bytes - JAVA

I'm trying to implement a database in java using slotted pages , so basically what I want to do is to store my data in a specific number of bytes . so this is the page where I have to store it .

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

now I want to store an Integer in the first 4 bytes of myData , when I do that automatically is stored in just one byte if the Integer doesn't exceed 255 , but what I want to do is use 4 bytes for my Integer it doesn't matter if it's 1 or one billion .

my question is , is it possible to do that in java ? to control how many bytes my data must allocate , like I assign 3 to the first 4 bytes of my byte array ?.

        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, 0,data,offset,record.getFixedLength());
            System.arraycopy(var_rec, 0,data,offsetEnd,record.getVariableLength());
            read_bytes(data);
            this.numRecords++;
            }else {

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

            }

I have a fixed-sized variables that I need to store them in my case for example in 12 bytes , I have been using System.arraycopy() but it's not relevant in my case , after I execute the code I get out of bound exception "last source index 12 out of bounds for byte[9]" because it uses just 9 bytes to store my Data not 12 .

Upvotes: 0

Views: 993

Answers (1)

dguy
dguy

Reputation: 140

This method creates an array of 32 bytes of any integer given - be it 1 or one billion:

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;
    }

You have an array of byte ready to store:

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

You have a hand-picked integer as well:

    BigInteger myInteger = new BigInteger("50000000000");

Then we change our integer to 32-length byte[]

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

Finally, you copy first 4 bytes of integer to your byte[] myData

    System.arraycopy(bytesOfInteger, 0, myData, 0, 3);

So this shows that you can allocate any decent big integer into a fixed 32 byte[].

Upvotes: 1

Related Questions