Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
trying to understand bitwise operations
I come across a lot of bitwise operators when I look at the functions included in QM. So, I read about Bitwise operation on Wikipedia and understand how bitwise operators work on binary numbers, but I still don't understand how they work on variables and values in QM. For example, could some one tell me how to understand things like: if(flags&2=0). Is that the same as if(flags=2) ? If not, how do they differ?
Binary is not a different kind of a number. It is one of ways you can write a number. You can write the same number in decimal, hexadecimal, binary or some other format. In QM you can write numbers in decimal and hexadecimal format. In QM you cannot write numbers in binary format, but you can imagine.

decimal binary
0 00000000
1 00000001
2 00000010
3 00000011
4 00000100
5 00000101

Example of 5&3:
decimal binary
5 00000101
3 00000011
1 00000001

Compare each column. If both numbers contain 1 in the same column, then result will contain 1 in that column. Else result will contain 0 in that column.


if(flags=2) and if(flags&2) are different. if(flags=2) is true only if flags is exactly 2. if(flags&2) is true if flags contains 1 in 2-nd column from the right (because 2 contains 1 in that column). It is true if flags is 2, 3, 6, 7 and so on. if(flags&4) is true if flags contains 1 in 3-rd column from the right (because 4 contains 1 in that column).
Ok, so how are multiple values for a variable represented in binary? For example: flags = 1|2
And how would I test for each value, because this doesn't work: if(flags=1).
This is actually the core of my question.
I am trying to write a function that allows multiple flags, but I don't know how to test for specific values.
So, I looked at your code and that's when I found all the bitwise operations like: if(flags&2=0).
Usually, caller passes flags using operator |, and function checks each flag using operator &. Flags can be 1, 2, 4, 8, 16, 32, 64, 128, 0x100, 0x200, 0x400, 0x800, 0x1000, and so on, until 0x80000000. Max 32 flags possible. You don't need to use or imagine how it looks in binary format.

Copy      Help
Function35 1|2

Function Function35
Copy      Help
function flags
,out "flag 1 is set"
,out "flag 2 is set"


Copy      Help
function flags
,out "flag 1 is not set"
,out "flag 2 is not set"

Forum Jump:

Users browsing this thread: 1 Guest(s)