Search code examples
autoit

How to avoid sign extension with AutoIT BitShift()?


While trying to port an algorithm from C, I have determined that the AutoIT BitShift( ) function does sign extension if the high bit of a 32-bit field is set.

    ConsoleWrite("Bit shift test: (0x80112233 >> 4)=" & hex(BitShift(0x80112233,4)) & @CRLF) ;### Debug Console
    ConsoleWrite("Bit shift test: (0x60112233 >> 4)=" & hex(BitShift(0x60112233,4)) & @CRLF) ;### Debug Console

Bit shift test: (0x80112233 >> 4)=F8011223
Bit shift test: (0x60112233 >> 4)=06011223

See how the first test adds an 'F' to the front.

I think I'm straying outside the normal operations of AutoIT (not a lot of documentation on BitShift and BitRotate, and I don't see anybody else that ran into this problem), but I'm hoping somebody has an easy fix for this.

I'm using 3.6.6 of SciTe, if that matters.


Solution

  • I don't consider current BitShift() working wrong. Official documentation says this:

    Bit operations are performed as 32-bit integers.

    Since it doesn't say "as unsigned 32-bit integers", sign extension seems quite OK.

    However, I don't see you point. If you know desired behavior, why not implementing custom function to fit your needs? Here is my variant:

    Func BitShiftUnsigned($value, $shift)
        If $shift > 0 Then
            Return BitAnd(BitShift($value,$shift), BitShift(0x7fffffff, $shift-1))
        Else
            Return BitShift($value,$shift)
        EndIf
    EndFunc