Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在 C# 中有一个短变量,想更改一个特定的位。我怎样才能做到最简单的方法?
你的意思是这样的吗?
public static short SetBit(short input, int bit) { return (short) (input | (1 << bit)); } public static short ClearBit(short input, int bit) { return (short) (input & ~(1 << bit)); }
如果你愿意,你甚至可以让它们成为扩展方法。
看一下按位运算符:
short i = 4; short k = 1; Console.WriteLine(i | k); //should write 5
您可以在此处查看Logical (boolean and bitwise)该部分下的操作员列表。
Logical (boolean and bitwise)
另外,做了一些探索,发现了这个按位辅助类。根据您的需要,可能值得一试。