不,c#中没有四位数据类型.
顺便提一下,4位只存储0到15之间的数字,因此如果存储0到127之间的值,它听起来不适合用于目的.要计算变量的范围,只要它有N位,使用公式(2^N)-1计算最大值.2 ^ 4 = 16 - 1 = 15.
如果需要使用小于8位的数据类型以节省空间,则需要使用压缩二进制格式和特殊代码来访问它.
例如,您可以使用AND掩码和位移存储一个字节中的两个四位值
byte source = 0xAD;
var hiNybble = (source & 0xF0) >> 4; //Left hand nybble = A
var loNyblle = (source & 0x0F); //Right hand nybble = D
Run Code Online (Sandbox Code Playgroud)
或者使用整数除法和模数,这也很有效,但可能不太可读:
var hiNybble = source / 16;
var loNybble = source % 16;
Run Code Online (Sandbox Code Playgroud)
当然,您可以使用扩展方法.
static byte GetLowNybble(this byte input)
{
return input % 16;
}
static byte GetHighNybble(this byte input)
{
return input / 16;
}
var hiNybble = source.GetHighNybble();
var loNybble = source.GetLowNybble();
Run Code Online (Sandbox Code Playgroud)
存储它更容易:
var source = hiNybble * 16 + lowNybble;
Run Code Online (Sandbox Code Playgroud)
只更新一个nybble更难:
var source = source & 0xF0 + loNybble; //Update only low four bits
var source = source & 0x0F + (hiNybble << 4); //Update only high bits
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6120 次 |
| 最近记录: |