Difference between revisions of "Operator Reference"

2,314 bytes added ,  16:37, 24 June 2018
m
→‎Note: Made the first sentence easier to read by swapping the order of the hexadecimal and decimal example values.
imported>Mattamue
imported>Homecom
m (→‎Note: Made the first sentence easier to read by swapping the order of the hexadecimal and decimal example values.)
 
(4 intermediate revisions by 2 users not shown)
Line 65: Line 65:
; i will get the string "Hello World"
; i will get the string "Hello World"
i = "Hello " + "World"
i = "Hello " + "World"
</source>
=== Note ===
In the past, there was concern about the correctness of the [https://en.wikipedia.org/wiki/Modulo_operation modulo] (<code>%</code>) operator when applied to negative integers such as -2,147,483,647 (0x80000001). Those concerns were unfounded.
''The modulo operator produces correct results in all cases'', but it must be understood that the result will have the sign of the dividend in Papyrus (as in Java and many other languages), therefore <code>3 % 2 == 1</code> and <code>-3 % 2 == -1</code>.
A specific case of concern was the calculation necessary to isolate the low-order 3 bytes (6 nibbles, or 24 bits) of an integer, which requires a modulo operation with a divisor of 2^24 (AKA 0x01000000 or 16,777,216). When that modulo operation is applied to dividends in the range -2,147,483,647 (0x80000001) to -1 (0xFFFFFFFF), inclusive, the results correctly range from -16,777,215 (0xFF000001) to -1 (0xFFFFFFFF). However, the goal of isolating the low-order 3 bytes of the integer (performing an operation equivalent to a bit-wise AND with 0x00FFFFFF) is ''not'' met in those cases. In order to meet that goal, negative values must be handled specially. For example:
<source lang="papyrus">
int Function getLow3Bytes(int i)
{Set the high 8 bits of i to zero, and return the low 24 bits intact.
Equivalent to "i & 0x00FFFFFF" in C, Java, etc.}
    if i < 0
        ; Force i to be a positive number, by changing its high bit (bit 32) from 1 to 0.
        i += 0x80000000
    endIf
    return i % 0x01000000
EndFunction
</source>
Such emulation of bit-wise operations using mathematical operations is a little more complicated when the high bit must be preserved:
<source lang="papyrus">
int Function getHighByteAsLowByte(int i)
{Return the high byte of i as a value between 0 and 255 (0x00-0xFF), inclusive.
Equivalent to "i >> 24 & 0xFF" in C, Java, etc.}
    if i < 0
        ; Force i to be a positive number, by changing its high bit (bit 32) from 1 to 0.
        ; Then divide by 0x01000000 (16,777,216), which is now equivalent to a right shift of 24 bits.
        ; Finally, restore the value of the high bit we cleared, now that it is bit 8 and cannot affect the sign.
        return (i + 0x80000000) / 0x01000000 + 0x80
    endIf
    return i / 0x01000000
EndFunction
</source>
</source>


Anonymous user