没有更具体的问题,特别是您展示了迄今为止的代码并解释了您遇到的问题具体来说就让它发挥作用而言,很难确切地知道最好的答案是什么。
也就是说,这里有一些示例方法可能会为您指明正确的方向:
// Stores the given value in storage at the given index
int Set(int storage, int value, int index)
{
int shiftCount = index * 5,
mask = 0x1f << shiftCount;
return (storage & ~mask) | (value << shiftCount);
}
// Retrieves the value stored in storage at the given index
int Get(int storage, int index)
{
int shiftCount = index * 5,
mask = 0x1f << shiftCount;
return (storage & mask) >> shiftCount;
}
The Set()
上面的方法获取当前值storage
,清除要存储五位值的位范围内的所有位,然后使用|
运算符来存储该五位值,首先将该值的位移到正确的位置。
The Get()
方法执行相反的操作。它屏蔽(清除)所有位not在存储值的位范围内,然后将存储的位下移到一个最低有效的五位int
在返回该结果之前。
Notes:
- 以上是针对您所提到的问题的具体内容。通过封装在一个类中可以很容易地概括它,其中可以在初始化时配置位计数,并且掩码是基于该位计数生成的,而不是硬编码的。
- 上面的代码没有进行错误检查。在生产代码版本中,最好验证
value
传递给Set()
方法实际上适合五位(即小于0x20
).
EDIT:
这是一个简单的控制台程序,使用示例数据演示了上述内容的用法:
static void Main(string[] args)
{
int[] array = { 31, 6, 23, 31 };
int storage = 0;
storage = ArrayToStorage(array, storage);
Console.WriteLine(storage);
LogArray(array);
storage = Set(storage, 9, 1);
storage = Set(storage, 17, 2);
StorageToArray(array, storage);
Console.WriteLine(storage);
LogArray(array);
}
static int ArrayToStorage(int[] array, int storage)
{
for (int i = 0; i < array.Length; i++)
{
storage = Set(storage, array[i], i);
}
return storage;
}
static void StorageToArray(int[] array, int storage)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = Get(storage, i);
}
}
static void LogArray(int[] array)
{
Console.WriteLine("[" + string.Join(", ", array) + "]");
}
// Stores the given value in storage at the given index
static int Set(int storage, int value, int index)
{
int shiftCount = index * 5,
mask = 0x1f << shiftCount;
return (storage & ~mask) | (value << shiftCount);
}
// Retrieves the value stored in storage at the given index
static int Get(int storage, int index)
{
int shiftCount = index * 5,
mask = 0x1f << shiftCount;
return (storage & mask) >> shiftCount;
}