简体   繁体   English

将多组数字存储到字节数组中

[英]Storing multiple sets of numbers into a byte array

I have a memory register 56 bytes big, and I have 4 different numbers I need to store in the register. 我有一个56字节大的内存寄存器,我有4个不同的数字,我需要存储在寄存器中。

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? 由于我只能将最多255个存储到一个字节中,如何使用这些字节的组合来适应所有内容?

As I mentioned before, they're not a fixed size and can range from 0-99999. 正如我之前提到的,它们不是固定的大小,可以在0-99999之间。

Since you have plenty of memory to spare(see blinkenlight's comment), I'd give each number three bytes. 由于你有足够的内存(参见blinkenlight的评论),我给每个数字三个字节。

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

56 bytes should be more than enough to store 4 such numbers. 56个字节应该足以存储4个这样的数字。 An Int32 is 4 bytes long and can store values up to 2,147,483,647. Int32长度为4个字节,可以存储最多2,147,483,647的值。 So, you need only 16 (4x4) bytes on your 56 bytes memory register. 因此,您的56字节内存寄存器只需要16(4x4)个字节。 You can store the values using the first 16 bytes of the memory register and leave the remaining 40 bytes unused. 您可以使用存储器寄存器的前16个字节存储这些值,并将剩余的40个字节保留为未使用状态。 To read and write bytes to and from the register, you can use the BitConverter class. 要从寄存器读取和写入字节,可以使用BitConverter类。

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). 我希望你不是指56位,在这种情况下你每个值有14位(16384),这对于你需要存储的最大值(99999)来说还不够大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM