问题描述
C#是否具有 4位数据类型?我想用一个浪费最小内存的变量制作程序,因为该程序会消耗很多内存.
Does C# have a 4 bit data type? I want to make a program with variables that waste the minimum amount of memory, because the program will consume a lot.
例如:我需要保存一个我知道它将从 0
变为 10
的值,并且可以使用 4位变量从 0
到 15
完美.但是我发现最接近的是8位(1字节)数据类型 Byte .
For example: I need to save a value that i know it will go from 0
to 10
and a 4 bit var can go from 0
to 15
and it's perfect. But the closest i found was the 8 bit (1 Byte) data type Byte.
我有一个用自定义数据类型创建 c ++ dll 的想法.轻咬之类的东西.但是,如果这是我的问题的解决方案,那么我不知道从哪里开始以及我该怎么做.
I have the idea of creating a c++ dll with a custom data type. Something like nibble. But, if that's the solution to my problem, i don't know where to start, and what i have to do.
局限性:否是创建字节并将其分成两部分的一种选择.
Limitations: Creating a Byte and splitting it in two is NOT an option.
推荐答案
不,在c#中不存在四位数据类型的问题.
No, there is no such thing as a four-bit data type in c#.
顺便说一句,四个位将只存储一个0到15的数字,因此,如果您存储的是0到127的值,这听起来似乎不合适.N位,使用公式(2 ^ N)-1
计算最大值.2 ^ 4 = 16-1 = 15.
Incidentally, four bits will only store a number from 0 to 15, so it doesn't sound like it is fit for purpose if you are storing values from 0 to 127. To compute the range of a variable given that it has N bits, use the formula (2^N)-1
to calculate the maximum. 2^4 = 16 - 1 = 15.
如果您需要使用小于8位的数据类型以节省空间,则需要使用和用于访问它的特殊代码.
If you need to use a data type that is less than 8 bits in order to save space, you will need to use a packed binary format and special code to access it.
例如,您可以使用AND掩码加上一个位移,将两个四个四位值存储在一个字节中,例如
You could for example store two four-bit values in a byte using an AND mask plus a bit shift, e.g.
byte source = 0xAD;
var hiNybble = (source & 0xF0) >> 4; //Left hand nybble = A
var loNyblle = (source & 0x0F); //Right hand nybble = D
或者使用整数除法和模数,也可以很好地工作,但是可读性可能不高:
Or using integer division and modulus, which works well too but maybe isn't quite as readable:
var hiNybble = source / 16;
var loNybble = source % 16;
当然可以使用扩展方法.
And of course you can use an extension method.
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();
存储起来更容易:
var source = hiNybble * 16 + lowNybble;
仅更新一个半字节就比较困难:
Updating just one nybble is harder:
var source = source & 0xF0 + loNybble; //Update only low four bits
var source = source & 0x0F + (hiNybble << 4); //Update only high bits
这篇关于C#4位数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!