C# C语言中的最短方法“写入类型常量”;字节";使用按位求反运算符?
这是一个有点“软问题”,但基本上我尝试采用这种模式,利用隐式转换为字节:C# C语言中的最短方法“写入类型常量”;字节";使用按位求反运算符?,c#,C#,这是一个有点“软问题”,但基本上我尝试采用这种模式,利用隐式转换为字节: byte x = 0; x |= 2; // implicit conversion of "x | 2" to byte here 并将其用于删除位: 我能想出的最短答案是: x &= unchecked((byte) ~2); (此时,我开始认真考虑只写x&=253;//~2,或者只写旧的显式转换:x=(字节)(x&~2);) 我错过了一条较短的路吗 byte x = 6; Console.Wr
byte x = 0;
x |= 2; // implicit conversion of "x | 2" to byte here
并将其用于删除位:
我能想出的最短答案是:
x &= unchecked((byte) ~2);
(此时,我开始认真考虑只写x&=253;//~2
,或者只写旧的显式转换:x=(字节)(x&~2);
)
我错过了一条较短的路吗
byte x = 6;
Console.WriteLine(x & ~(byte)2);
这对我有用,打印4张这张怎么样:
{
byte x = 0;
x |= 2;
x &= 0xFF & ~2;
}
说明:这里有两个问题。首先,一元运算符“~”:
根据C#规范4.1.5:
整数类型的一元和二元运算符总是使用有符号
32位精度,无符号32位
精度、有符号64位精度或
无符号64位精度:
对于一元+和~运算符,操作数转换为T类型,
其中T是int的第一个,uint,
长,和乌龙,可以充分
表示的所有可能值
操作数。那么手术就结束了
使用类型的精度执行
T、 结果的类型是T
应用一元运算符后,结果始终是最小的“int”类型。从那里,您希望隐式转换为字节
其次:
int-can类型的常量表达式
转换为sbyte、byte、short、,
ushort、uint或ulong,前提是
常量表达式的值为
在目的地范围内
类型
所以,~2始终是一个int。它不能隐式转换为byte,因为它超出了范围。如果将其限制在范围内,则可以隐式转换。使用自定义类型
public struct Bits
{
byte x;
public Bits(int x) { this.x = (byte)x; }
public Bits(byte x) { this.x = x; }
public Bits(Bits x) { this.x = x.x; }
public static implicit operator byte(Bits x) { return x.x; }
public static implicit operator Bits(byte x) { return new Bits(x); }
public static implicit operator Bits(int x) { return new Bits(x); }
}
static void Main(string[] args)
{
Bits x = 0;
x |= 2;
x &= ~2;
}
此外,您还可以为字节编写en扩展方法来设置位
public static byte Set(this byte x, byte v)
{
return (byte)(x | v);
}
public static byte Unset(this byte x, byte v)
{
return (byte)(x & ~v);
}
static void Main(string[] args)
{
byte x = 0;
x = x.Set(2);
x = x.Unset(2);
}
可以用以下方式命名常量:
[Flags]
enum SomeType : byte {
Value = 2,
}
public void Method () {
SomeType t = 0;
t |= SomeType.Value;
t &= ~SomeType.Value;
}
是的,它是有效的,但是否定的结果是类型
int
。尝试删除(byte)
强制转换-它仍然可以工作。哦,我明白了,问题是byte不喜欢任何“负数”。可以执行x=(字节)(x&~2);这是一个很好的观点;如果我要开始使用替代方案,我不妨回到显式转换。不过,这个问题仍然存在。
[Flags]
enum SomeType : byte {
Value = 2,
}
public void Method () {
SomeType t = 0;
t |= SomeType.Value;
t &= ~SomeType.Value;
}