This is what I came up with.
I love AHK!!!
Code: Select all
IsEvenNumber(int) {
if (InStr(int/2, ".5"))
return 0
return 1
}
Code: Select all
IsEvenNumber(int) {
if (InStr(int/2, ".5"))
return 0
return 1
}
Code: Select all
IsEvenNumber(int) {
if (Mod(int, 2) = 0)
return 1
return 0
}
Code: Select all
if ! (int & 1) ; 'int' is even
Code: Select all
IsEvenNumber(int) { ; works with pure integers only
return (int & 1) ? 0 : 1
; Test LSB (least significant bit) to check if int is uneven.
; return 0 if bit is set
; return 1 if bit is not set
;
; int MSB LSB
; | V v
; -2 (decimal) = 11111110 (binary)
; -1 (decimal) = 11111111 (binary)
; 0 (decimal) = 00000000 (binary)
; 1 (decimal) = 00000001 (binary)
; 2 (decimal) = 00000010 (binary)
; 3 (decimal) = 00000011 (binary)
; 4 (decimal) = 00000100 (binary)
; 5 (decimal) = 00000101 (binary)
; ...
}
Code: Select all
TestSection:
loop 5 {
if (x := IsEvenNumber(A_Index))
MsgBox ,,call IsEvenNumber(%A_Index%), Result: %x% -> %A_Index% is even
else
MsgBox ,,call IsEvenNumber(%A_Index%), Result: %x% -> %A_Index% is not even
if (x := IsEvenNumber(-A_Index))
MsgBox ,,call IsEvenNumber(-%A_Index%), Result: %x% -> -%A_Index% is even
else
MsgBox ,,call IsEvenNumber(-%A_Index%), Result: %x% -> -%A_Index% is not even
}
; if speed is desired, no need to call a function: use LSB-Test inline:
loop 5 {
if A_Index & 1
MsgBox ,,inline test LSB (%A_Index% & 1), Result: %A_Index% is not even
else
MsgBox ,,inline test LSB (%A_Index% & 1), Result: %A_Index% is even
}
Nice. Your explanation could be enhanced for those new to bitwise operations by also showing some examples of the operation in table form.
Code: Select all
; 4 in binary: 100
; 1 in binary: 001
; =
; bitwise AND: 000
; 9 in binary: 1001
; 1 in binary: 0001
; =
; bitwise AND: 0001
This has always been something I've tried to avoid. I've also never tried to learn it... I'm sure it would help me greatly especially when dealing with CLR. I always make wrapper classes because I do not know how to do the bitwise maths or where to start really. I had issues with this early in the .Net Framework thread.neogna2 wrote: ↑19 Apr 2021, 12:19Code: Select all
; 4 in binary: 100 ; 1 in binary: 001 ; = ; bitwise AND: 000 ; 9 in binary: 1001 ; 1 in binary: 0001 ; = ; bitwise AND: 0001
Code: Select all
MsgBox % 5 & 3 ; output: 1
;bin 0101 = dec 5
;bin 0011 = dec 3
; &
;bin 0001 = dec 1
Yes, but not because the bits are different but because they are not both 1. In other words for each pair of corresponding bits the bitwise AND (&) operation outputs 1 if both operands are 1 and otherwise (in the other three possible cases) outputs 0.
https://en.wikipedia.org/wiki/Bitwise_operation#ANDA bitwise AND is a binary operation that takes two equal-length binary representations and performs the logical AND operation on each pair of the corresponding bits
Return to “Scripts and Functions (v1)”
Users browsing this forum: No registered users and 95 guests