power of 2 and binary numbers...
In VB, I'm going to have a set of flag constants that are powers of 2 (1,2,4,8,16,32,64, etc) so that my flag variable (a long integer) can have many combinations of those flags (using 'Or' to build the value and 'And' to read it)
Anyways, how can I take a number that's made up of 2 or more of these flags, and then find out which bits in the number are set to 1
Example..
VB Code:
const flag1 = 2 '0000 0010
const flag2 = 8 '0000 1000
Dim L As Long
Dim I As Integer
L = flag1 Or flag2 ' L is 0000 1010
If (L And flag1) = flag1 Then
I = ' code to find which bit in flag1 is turned on (should return 2)
Msgbox "The " & i & "nd bit is on"
End If
If (L And flag2) = flag2 Then
I = ' code to find which bit in flag2 is turned on (should return 4)
Msgbox "The " & i & "th bit is on"
End If
So basically, I need to know how to know which power of 2 a number is.
Re: power of 2 and binary numbers...
Quote:
Originally posted by brenaaro
...
...So basically, I need to know how to know which power of 2 a number is.
Strictly speaking, the fastest way to do it is by directly calculating the power:
i = log(flag) / log(2)
(the log can be any base as long as it's the same both for the numerator and the denominator)
This could however lead to nasty surprises because of roundoff so, a more reliable way to do it would be something like:
VB Code:
i = 0
k = flag
Do While k > 1
k = k \ 2 'Notice: \ means integer division
i = i + 1
Loop
'So that i is the result you want
'Btw, the rightmost bit is number 0
Re: power of 2 and binary numbers...
[QUOTE]Originally posted by brenaaro
So basically, I need to know how to know which power of 2 a number is.
Why?
The code you have is exactly what you need, you just need to put in the code to do the work.
VB Code:
const flag1 = 2 '0000 0010
const flag2 = 8 '0000 1000
Dim L As Long
Dim I As Integer
L = flag1 Or flag2 ' L is 0000 1010
If (L And flag1) = flag1 Then
'Flag1 is set - so run appropriate code
Else
'Flag1 is NOT set - so run appropriate code
End If
If (L And flag2) = flag2 Then
'Flag2 is set - so run appropriate code
Else
'Flag2 is NOT set - so run appropriate code
End If