ByteArray Class

Write a class called ByteArray that implement allocating, reading and writing to an array of bytes. The runtime environment has a limitation. The maximum continuous memory size that it can allocated is 64k bytes. It can allocate many 64K ( or less) chunks.
The ByteArray class should hide this limitation and support allocating arrays larger than 64K as in the following example :

ByteArray ba = new ByteArray (250000); // Create
ba[150000] = 15; // Write byte
byte x = ba[190000]; // Read byte

Questions by wailoon.ho

Showing Answers 1 - 2 of 2 Answers

Raedon

  • Jan 25th, 2011
 

class ByteArray
    {
        private byte[] byteArray;

        public byte this[int index]
        {
            get { return byteArray[Validate(index)]; }
            set { byteArray[Validate(index)] = value; }
        } 

        public ByteArray(int lenght)
        {
            byteArray = new byte[Validate(lenght)];
        }

        private int Validate(int lenght)
        {
            int result = lenght;
            if (!((lenght > 0) && (lenght <= 65535)))
            {
                Debug.Fail("The index is out of range.");
                result = 0;
            }
            return result;
        }

    }

  Was this answer useful?  Yes

    class ByteArray
    {
        // using jagged array as store
        byte[][] storage;
        // maximum amount of data in block
        const int MAX_BLOCK = 65536;

        public ByteArray(int capacity)
        {
            // number of blocks needed
            int n = (int)Math.Ceiling(capacity / (double)MAX_BLOCK);
            // capacity of last block
            int lastBlock = (n == 1) ? capacity : capacity % MAX_BLOCK;
            // creating storage
            storage = new byte[n][];
            for (int block = 0; block < n; block++)
                if (block == n - 1) // last block custom capacity
                    storage[block] = new byte[lastBlock];
                else
                    storage[block] = new byte[MAX_BLOCK];
        }

        public byte this[int index]
        {
            get
            {
                int block = index / MAX_BLOCK;
                int element = index % MAX_BLOCK;

                return storage[block][element];
            }
            set
            {
                int block = index / MAX_BLOCK;
                int element = index % MAX_BLOCK;

                storage[block][element] = value;
            }
        }
    }

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions