Jump to content

Bit Masking and math functions


silhouett

Recommended Posts

Id like to take a dec number and using masking as in And / OR etc be able to tell if a single binary bit in that dec number is on or off and to be able to set or unset that bit

for example

 

16 is actually 8 4 2 1 as binary positions go thus is there a math function that I could say do

1 1 1 1

 

16 (some operator) 8 and have it change to number 7 as I turned off the 8

! 1 1 1 1 0 0 0 0 1 1 1

and then do

 

16 (some operator) 8 and have it change back to 16 as I turned on the 16

! 1 1 1 1 0 0 0 ! 1 1 1

 

then also important is there a way I could mask the 16 to see if the 8 was on or off ?

I want to do this with 255 or 512 to be able to store flags in a Global variable thus cutting down the Global Variable usage.

Link to comment
Share on other sites

I can help with this. You will need to covert this a bit for your scripting language, but this will work.

 

Bitarray= New Array(16);

Bittest= New Array(16);

T=16;

z=16;

K=0;

For (z=16;t>-1;t--)

{

Bitarray[z]=2^t;

z=z-1;

}

//This should set up the 512 array, biggest last. This next step will help when breaking down a variable.

 

Function var_split(var globalsets)

{

G=globalsets;

Splits= New Array (16);

Y=16;

D=16;

For(Y=16;Y>-1;Y--)

{

If (G=>Bitarray(Y))

{

Splits(Y)=1;

G=G-Bitarray(Y);

}

}

Return Splits;

}

 

Then all you have to do is feed the function the number variable. What picks up your flags will be the array created at the start. Example: Bittest=var_split(56);

 

 

Hope this helps, it is some lower level C, C++, or JavaScript coding. You can get some books on using arrays with the various programming languages pretty cheap, see w3c.org for the JavaScript coding (it's free).

Link to comment
Share on other sites

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...