I'm trying to write a function that returns the number of bits set in a 32-bit integer in VBScript, it's just for practising the language. The function I've written so far looks okay, but I'm wondering if there was a simpler solution.
Function countBits(value)
Dim n : n = 0
Dim mask : mask = 1
Dim i
For i = 0 to 30
If (value And mask) > 0 Then
n = n +1
End If
Next
If (value And &h8000) then
n = n+1
End If
countBits = n
End Function
I found that there are no shift operators in VBScript and an overflow (Err.Number = 6
) if I iterate for 0 to 31, that's why I add the explicitly check of the MSB after the look.
Any solutions to improve (maybe generalize) this?
edit: removed the useless error handling part, as it's a remains of starting with 31 as an upper bound in the first (and at that time only) loop