in reply to Re: bitwise operators
in thread bitwise operators

Bitwise operators are a lot more useful when doing system level programming in Assembler, C ,etc.

Around the early 90's when I was writing 3D texture mapped engines designed for 386/386sx+ systems (16 Megahertz!), I used them constantly. You can use bitshifts and bitlogic to do quick (and dirty) multiplies/divides by powers of 2, cheap modulus operations, collision detection, etc. Under those constraints, every clock cycle counts. At that time, you had to roll your own video drivers which meant screwing around with SVGA registers (all bit-masking)and all other arcane kind of things.

That said, if you are doing system level programming you will probably use them quite often.

To be honest, I haven't ever had the need (yet) to use them in any Perl applications.



-Lee

"To be civilized is to deny one's nature."

Replies are listed 'Best First'.
Re: Re: Re: bitwise operators
by Anonymous Monk on May 29, 2001 at 03:05 UTC
    Bit fields, a componet which goes along with bitwise operators, are an important part of C(and C++). You can use them to save space: struct { UINT flag_a : 1; UINT flag_b : 1; } struct_name; (where as UINT is defined to be unsigned int). This is useful in saving memory, by combining many variables(flag_a and flag_b, in this case) together; we can do this because we only concern ourself with true/false value(0/1, respectively). In perl(as far as I know), you cannot do this automatically, but you can still make a scalar and use it to turn on and off certain values, and check certain values. For example: assume an eight bit integer(well, getting back to perl, scalar) 00000011 Here, we have the last two bits set. If we want to know if the second to last bit(i.e.,2nd rightmost) is set, then we can say: if(($scalar_here >> $number_to_shift_by) & $mask) #in this case, $number_to shift_by would be 1; and $mask would be a value such that all bits but the rightmost would be off; i.e., 00000001. To set the bit, we would say $scalar |= $mask, where as if we want to set the second right most bit, $mask should be a value where as all bits are off except the second right most: e.g., 00000010. We use or so that if it is on it stays on; however, if we want to say turn it on, except if it is already on, turn it off, we substitute |= with &=. Another use for bitwise operations is to substitute two values without using a temporary variable: e.g.,
    #var1= 0011 var2 = 1100 (only stating last
    # 4 bits, of cousre)
    $var1 ^= $var2; # v1=1111
    $var2 ^= $var1; # v2=0011
    $var1 ^= $var2; # v1=1100