如何更改字节变量中的每一位
How can change every bit in byte variable
我有一个字节数
// in decimal
byte number = 250
// result who I want is number = 5
// in binary
byte number = 0b11111010
// result who I want is number = 0b00000101
如何反转这个数字中的每一位?我尝试左移、右移操作、OR 和 AND,但没有按照我的需要进行操作。
使用按位 not
运算符 ~
byte b = 0b11111111;
byte flipped = ~b; // 0b00000000
编辑:来自 MSDN 的解释
The ~ operator looks at the binary representation of the values of the expression and does a bitwise negation operation on it.
Any digit that is a 1 in the expression becomes a 0 in the result. Any digit that is a 0 in the expression becomes a 1 in the result.
When the ~ operator acts on an operand of an integral data type, it performs no coercion and returns a value of the same data type as the operand. When the operand is of a non-integral data type, the value is coerced to type int before the operation is performed, and the return value of the operator is of type int.
我有一个字节数
// in decimal
byte number = 250
// result who I want is number = 5
// in binary
byte number = 0b11111010
// result who I want is number = 0b00000101
如何反转这个数字中的每一位?我尝试左移、右移操作、OR 和 AND,但没有按照我的需要进行操作。
使用按位 not
运算符 ~
byte b = 0b11111111;
byte flipped = ~b; // 0b00000000
编辑:来自 MSDN 的解释
The ~ operator looks at the binary representation of the values of the expression and does a bitwise negation operation on it. Any digit that is a 1 in the expression becomes a 0 in the result. Any digit that is a 0 in the expression becomes a 1 in the result. When the ~ operator acts on an operand of an integral data type, it performs no coercion and returns a value of the same data type as the operand. When the operand is of a non-integral data type, the value is coerced to type int before the operation is performed, and the return value of the operator is of type int.