Break down an HEX variable into binary

0

Good morning, everyone. I have a problem and I can not find the formula to solve it. I have a hexadecimal number (8000) and it is composed of 16 bits that each of them tell me the state of 16 things. I would like to separate that variable to use its bits individually, what would be the best way to do it?  e.g; 8000 (HEX) = 1000000000000000 (BIN) So, I would need to obtain 16 boolean variables and work with them independently ...

Thank you!

    
asked by Edulon 27.10.2016 в 07:23
source

1 answer

0

To work with the individual bits of a variable it is best to use "flags" that are predefined constants in which each one has a bit activated and that when performing a And operation with the variable indicates if that bit is activated .

For example:

FLAG_PARAMETRO1 = 1      // en binario 0000000000000001
FLAG_PARAMETRO2 = 2      // en binario 0000000000000010
FLAG_PARAMETRO3 = 4      // en binario 0000000000000100
FLAG_PARAMETRO4 = 8      // en binario 0000000000001000   
...

And so for the 16 variables you need. Then to know if a bit is activated in the variable you just have to compare with the corresponding flag:

If variable And FLAG_PARAMETRO4 = FLAG_PARAMETRO4 Then   
     // ese bit está en on
else
     // ese bit está en off
endif 

or you can also assign the value to a Boolean variable:

VarBool = (variable And FLAG_PARAMETRO4 = FLAG_PARAMETRO4)

Although it is not strictly necessary, because with the flags you have enough, but that to the taste of each one.

Another important utility of the use of flags is that you can check several bits at the same time using the operator Or :

VarFlag = (FLAG_PARAMETRO1 Or FLAG_PARAMETRO3) Or FLAG_PARAMETRO7

VarBool = (variable And VarFlag = VarFlag)

So you can know in a single comparison if several bits are active.

    
answered by 27.10.2016 в 09:04