Reputation: 6305
I have a memory register 56 bytes big, and I have 4 different numbers I need to store in the register.
The numbers could be
0-99999
0-99999
0-99999
0-99999
I have to store these in the same register as a single byte array. The problem is I'm not sure how I need to split it up between the four numbers and then read it back as four different numbers again given the size of them.
Since I can only store a max of 255 into a single byte, how do I use a combination of these bytes to fit everything in?
As I mentioned before, they're not a fixed size and can range from 0-99999.
Upvotes: 0
Views: 2052
Reputation: 151
56 bytes should be more than enough to store 4 such numbers.
An Int32
is 4 bytes long and can store values up to 2,147,483,647.
So, you need only 16 (4x4) bytes on your 56 bytes memory register.
You can store the values using the first 16 bytes of the memory register and leave the remaining 40 bytes unused.
To read and write bytes to and from the register, you can use the BitConverter
class.
I hope you didn't mean 56 bits, in which case you'd have 14 bits (16384) per value, which is not big enough for the max value you need to store (99999).
Upvotes: 0
Reputation: 108830
Since you have plenty of memory to spare(see blinkenlight's comment), I'd give each number three bytes.
public static uint Read3BE(byte[] data, int index)
{
return data[index]<<16 | data[index+1]<<8 | data[index+2];
}
public static void Write3BE(byte[] data, int index, uint value)
{
if((value>>24)!=0)
throw new ArgumentException("value too large");
data[index]=(byte)(value>>16);
data[index+1]=(byte)(value>>8);
data[index+2]=(byte)value;
}
Upvotes: 2