c# - practical applications of bitwise operations -
- what have used bitwise operations for?
- why handy?
- can please recommend simple tutorial?
although seems hooked on flags usecase, isn't application of bitwise operators (although common). c# high enough level language other techniques used, it's still worth knowing them. here's can think of:
the <<
, >>
operators can multiply power of 2. of course, .net jit optimizer (and decent compiler of language well), if you're fretting on every microsecond, might write sure.
another common use these operators stuff 2 16-bit integers 1 32-bit integer. like:
int result = (shortinta << 16 ) | shortintb;
this common direct interfacing win32 functions, use trick legacy reasons.
and, of course, these operators useful when want confuse inexperienced, when providing answer homework question. :)
in real code though you'll far better off using multiplication instead, because it's got better readability , jit optimizes shl
, shr
instructions anyway there no performance penalty.
quite few curious tricks deal ^
operator (xor). powerful operator, because of following properties:
a^b == b^a
a^b^a == b
- if know
a^b
it's impossible tella
,b
are, if know 1 of them, can calculate other. - the operator doesn't suffer overflows multiplication/division/addition/subtraction.
a couple of tricks have seen using operator:
swapping 2 integer variables without intermediary variable:
a = a^b // xor of , b b = a^b // b original a = a^b // original b
doubly-linked list 1 variable per item. have little use in c#, might come in handy low level programming of embedded systems every byte counts.
the idea keep track of pointer first item; pointer last item; , every item keep track of pointer_to_previous ^ pointer_to_next
. way can traverse list either end, yet overhead half of traditional linked list. here's c++ code traversing:
itemstruct *currentitem = firstitem, *previousitem=null; while ( currentitem != null ) { // work currentitem->data itemstruct *nextitem = currentitem ^ previousitem; previousitem = currentitem; currentitem = nextitem; }
to traverse end need change first line firstitem
lastitem
. that's memory saving right there.
another place use ^
operator on regular basis in c# when have calculate hashcode type composite type. like:
class person { string firstname; string lastname; int age; public int override gethashcode() { return (firstname == null ? 0 : firstname.gethashcode()) ^ (lastname == null ? 0 : lastname.gethashcode()) ^ age.gethashcode(); } }
Comments
Post a Comment