So continuing the Integers as Binary Options questions. I know to do all this in Objective-C just trying to figure out how to use it in AppleScript.
How can I perform the following.
Assuming all options are 1 bit
alignNone = 0, /* 0
alignLeft = 1 << 0, /* 1
alignRight = 1 << 1 , /* 2
alignLeftOrRight = 3 , /* 3
alignVertical = 1 << 3 , /* 4
alignHorizontal = 1 << 4 , /* 8
Combine Option
set options to (alignVertical | alignHorizontal | alignRight)
/* 14
& Option (not sure what it’s called but understand it’s use
set hasOption to (options & alignLeft) = alignLeft
set hasAnyOption to (options & (alignLeft | alignRight)) as boolean
set hasAnyOption2 to (options & alignLeftOrRight) as boolean
The Remove Option
set options to options &^ alignHorizontal
AppleScript doesn’t have any bitwise methods, so the typical operators mean something else - see the AppleScript Language Guide. In addition, the pipe | is used for creating identifiers that would normally not be legal, for example |# normally not a legal identifier!|.
To perform bit operations other than calling out to something that can, you need to do them yourself.
# Integer multiply and divide by 2 can be used for simple shifting:
set alignLeft to 1 -- 1 << 0 (1)
set alignRight to 1 * 2 -- 1 << 1 (2)
set alignVertical to 1 * 2 * 2 -- 1 << 2 (4)
set alignHorizontal to (1 * (2 ^ 3)) as integer -- 1 << 3 (8)
set alignHorizontal to 16 div 2 -- 16 >> 1 (8)
# To combine values is not too bad, just an integer add:
set options to (alignVertical + alignHorizontal + alignRight) -- 14
# To extract an individual bit is a little more work:
-- flag div mask mod 2 = 1 -- by bit value
set test1 to 31 div 8 mod 2 = 1
-- flag div (2 ^ mask) mod 2 = 1 -- by bit position
set test2 to 31 div (2 ^ 3) mod 2 = 1 -- 4th bit (LSB = 0)
There are also a few scripts on Rosetta Code that may be helpful for stuff a bit more involved, such as XOR or rotates.