Reputation: 335
I have a short-variable in C# and want to change a specific bit. How can I do it the easiest way?
Upvotes: 3
Views: 1259
Reputation: 1500735
Do you mean something like this?
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));
}
You could even make them extension methods if you want to.
Upvotes: 6
Reputation: 85056
Take a look at bitwise operators:
short i = 4;
short k = 1;
Console.WriteLine(i | k); //should write 5
You can see a list of the operators under the Logical (boolean and bitwise)
section here.
Also, did some poking around and found this bitwise helper class. Might be worth checking out depending on your needs.
Upvotes: 4