我需要一些C#方面的帮助
我需要在C#中开发一个模块,它将消耗大量的CPU&RAM,每一位都很重要
我假设要创建一个包含structs的列表,其中一个字段将是自定义的整数
整数只能是0,1,2(二进制:00,01,10)-所以我不需要大于2位的整数
这比最小的内置整数字节(有8位)要好
我需要新的整数作为正则整数,所以当我尝试进行简单的赋值或任何简单的算术计算时,我不需要使用强制转换(非常昂贵)或任何其他特殊操作
有没有一种方法可以在结构中定义自定义整数,而不更改主程序中的其余代码
如果你能给我写一个简短的结构或给我介绍一个类似的实现,我将不胜感激
非常感谢
"ushort,有4位"
不,ushort是16位。一个字节是最小的,有8位。
"有没有办法在结构中定义自定义整数,而不更改主程序中的其余代码?"
不,您不能生成小于一个字节的结构,因此要生成只使用两个位的整数,您必须更改包含这些位的集合,以便它可以在一个字节中存储多个值。
类似于:
public class TwoBitArray {
private int _len;
private byte[] _data;
public TwoBitArray(int size) {
_len = size;
_data = new byte[(size + 3) / 4];
}
public int this[int index] {
get {
if (index < 0 || index >= _len) throw new IndexOutOfRangeException();
int ofs = index / 4;
int shift = (index & 3) * 2;
return (_data[ofs] >> shift) & 3;
}
set {
if (index < 0 || index >= _len) throw new IndexOutOfRangeException();
if (value < 0 || value > 3) throw new ArgumentOutOfRangeException();
int ofs = index / 4;
int shift = (index & 3) * 2;
int mask = 3 << shift;
_data[ofs] = (byte)((_data[ofs] & (255 - mask)) | (value << shift));
}
}
}