Code: Select all
' SharpBASIC bitwise 2
' --------------------
option strict;
incl "lib/sys.sbi";
decl func PopBits(x: int): int;
decl func BitIsls(x: int): int;
dim x, n: int = 0;
main do
' bit n
n = 2;
' set bit n
x = (1 << n) ? x;
print(x); ' 4
' clear bit n
x = ~(1 << n) & x;
print(x); ' 0
' flip bit n
x = (1 << n) ! x;
print(x); ' 4
' convert trailing zero's
x = (x - 1) ? x;
print(x); ' 7
' count populated bits
n = PopBits(x);
print(n); ' 3
n = BitIsls(x);
print(n); ' 1
end;
' count populated bits (bits that are set to 1)
func PopBits(x: int): int
dim n: int;
do
loop do
until x == 0;
x = x & (x - 1);
n = n + 1;
end;
PopBits = n;
end;
' count groups of populated bits
func BitIsls(x: int): int
do
BitIsls = ((x & 1) + PopBits((x ! (x >> 1)))) / 2;
end;