According to wiki shifts can be used to calculate powers of 2:
A left arithmetic shift by n is equivalent to multiplying by 2^n (provided the value does not overflow), while a right arithmetic shift by n of a two's complement value is equivalent to dividing by 2^n and rounding toward negative infinity.
I was always wondering if any other bitwise operators (~
,|
,&
,^
) make any mathematical sense when applied to base-10? I understand how they work, but do results of such operations can be used to calculate anything useful in decimal world?
Bitwise operators in C should not be used with variable of type float. It is because they are stored in IEEE format (sign bit, exponent and mantissa).
Examples of uses of bitwise operations include encryption, compression, graphics, communications over ports/sockets, embedded systems programming and finite state machines. A bitwise operator works with the binary representation of a number rather than that number's value.
Bitwise operations are incredibly simple and thus usually faster than arithmetic operations. For example to get the green portion of an rgb value, the arithmetic approach is (rgb / 256) % 256 . With bitwise operations you would do something as (rgb >> 8) & 0xFF .
The bitwise operators have precedence and no special rules about avoid evaluation of subexpressions.
"yep base-10 is what I mean"
In that case, yes, they can be extended to base-10 in several ways, though they aren't nearly as useful as in binary.
One idea is that &
, |
, etc. are the same as doing arithmetic mod-2 to the individual binary digits. If a
and b
are single binary-digits, then
a & b = a * b (mod 2) a ^ b = a + b (mod 2) ~a = 1-a (mod 2) a | b = ~(~a & ~b) = 1 - (1-a)*(1-b) (mod 2)
The equivalents in base-10 would be (note again these are applied per-digit, not to the whole number)
a & b = a * b (mod 10) a ^ b = a + b (mod 10) ~a = 9-a (mod 10) a | b = ~(~a & ~b) = 9 - (9-a)*(9-b) (mod 10)
The first three are useful when designing circuits which use BCD (~a
being the 9's complement), such as non-graphing calculators, though we just use *
and +
rather than &
and ^
when writing the equations. The first is also apparently used in some old ciphers.
A fun trick to swap two integers without a temporary variable is by using bitwise XOR:
void swap(int &a, int &b) { a = a ^ b; b = b ^ a; //b now = a a = a ^ b; //knocks out the original a }
This works because XOR is a commutative so a ^ b ^ b = a.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With