35 lines
1.9 KiB
Plaintext
35 lines
1.9 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Certain https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/operators-and-expressions/logical-and-bitwise-operators#bitwise-operations[bitwise operations] are not needed and should not be performed because their results are predictable.
|
|
|
|
Specifically, using `And -1` with any value always results in the original value.
|
|
|
|
That is because the binary representation of `-1` on a https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/data-types/numeric-data-types[numeric data type] supporting negative numbers, such as `Integer` or `Long`, is based on https://en.wikipedia.org/wiki/Two%27s_complement[two's complement] and made of all 1s: `&B111...111`.
|
|
|
|
Performing `And` between a value and `&B111...111` means applying the `And` operator to each bit of the value and the bit `1`, resulting in a value equal to the provided one, bit by bit.
|
|
|
|
[source,vbnet]
|
|
----
|
|
anyValue And -1 ' Noncompliant
|
|
anyValue ' Compliant
|
|
----
|
|
|
|
Similarly, `anyValue Or 0` always results in `anyValue`, because the binary representation of `0` is always `&B000...000` and the `Or` operator returns its first input when the second is `0`.
|
|
|
|
[source,vbnet]
|
|
----
|
|
anyValue Or 0 ' Noncompliant
|
|
anyValue ' Compliant
|
|
----
|
|
|
|
The same applies to `anyValue Xor 0`: the `Xor` operator returns `1` when its two input bits are different (`1` and `0` or `0` and `1`) and returns `0` when its two input bits are the same (both `0` or both `1`).
|
|
When `Xor` is applied with `0`, the result would be `1` if the other input is `1`, because the two input bits are different, and `0` if the other input bit is `0`, because the two input are the same. That results in returning `anyValue`.
|
|
|
|
[source,vbnet]
|
|
----
|
|
anyValue Xor 0 ' Noncompliant
|
|
anyValue ' Compliant
|
|
----
|
|
|
|
include::../resources-dotnet.adoc[]
|
|
include::../rspecator.adoc[] |