Forum Discussion

kbenson's avatar
kbenson
Visitor
16 years ago

Suggestion box - more bitwise ops

Yeah, me again. I promise this time it's easier and more feasible

Any chance of getting bitwise xor, left shift and right shift ops? I've implemented my own, but it's nowhere near as fast. At least the shifts aren't. Xor is easy, but does require combining 5 other ops (and a function call, if you want it pretty).

3 Replies

  • I don't think we'll have these language primitive ops in the near future.... However, the logical operators or,and, and not are also bitwise operators.... So the operations you are asking for can be implemented in terms of those base bitwise operations.

    Example:


    a% = 6
    b% = 10
    print "a = ";a% ;" b = "; b%

    bitwiseAnd% = a% and b%
    bitwiseOr% = a% or b%
    bitwiseXOr% = bitwiseOr% and not bitwiseAnd%

    print "a xor b = "; bitwiseXOr%

    bitwiseLeftShift% = a% * 2

    print "a << 1 = "; bitwiseLeftShift%

    bitwiseRightShift% = a% / 2

    print "a >> 1 = "; bitwiseRightShift%


    --Kevin
  • Understood about the xor, it just seems that since there are the bitwise operations for AND, OR, and NOT, an XOR would be trivial to add and complete the offering.

    As for shift, left shifting is easy, because it's multiplication. Right shift is division, which results in a float. It's not as ideal. The following is what I have, and it works without division (which is key), but it's obviously nowhere near as fast as a native implementation would be:


    function rshift(num as integer, n=1 as integer) as integer
    mult = 2^n
    sumand = 1
    total = 0
    for i = n to 31
    if (num and sumand * mult)
    total = total + sumand
    end if
    sumand = sumand * 2
    end for

    return total
    end function
  • That's why I used the '%' character at the end of all my variables. That forces the types to be integers, and then the division to be integer division rather than floating point.

    --Kevin