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
| [reply] |