I'm using a programming language (more a scripting language) that does not support any bitwise operators like AND, OR, XOR, NOT (and shift as well).
Common arithmetic and logical operations like + - * / %>>= < <= == !=, logical AND, OR, NOT and control flow (while, for, if,...) are supported however. It is like a "subset of C", but without these binary operators. My question does not target that particular language anyway.
I was wondering if there is any (mathematical ?) way to set and check a bit at a specific position in a programming language that does not support bitwise operations :
a = 0; //00000000b
a = togglebit(a, 5); //00100000b
a = togglebit(a, 2); //00100100b
a = 0xFE; //11111110b
bool result = checkbit(a, 4); //true
For example, there is a way to perform a left or right binary shift using integer multiplication or division :
a = a * 2; //similar to left shift : a = a << 1;
a = a / 2; //similar to right shift : a = a >> 1;
I'm looking for something similar but for setting or checking a flag.
-
3The Wikipedia article on bitwise operations explains the mathematical equivalents, mostly they seem to be based on some modulo2 operations.thorsten müller– thorsten müller2014年08月30日 09:17:17 +00:00Commented Aug 30, 2014 at 9:17
1 Answer 1
To check the n th bit, shift right n times. If the bit is set, the result will be odd (numbers are odd if and only if their final bit is 1.)
function checkbit(a, n)
n times:
a = a / 2 (integer division)
return a % 2
end
To set the n th bit, add 2^n only if the bit is not yet set.
function pow2(n): (returns 2^n)
result = 1
n times: result = result * 2
return result
end
function setbit(a, n)
if checkbit(a, n):
return a
else:
return a + pow2(n)
end
Toggling it is similar, but we subtract if the bit is already set:
function togglebit(a, n)
if checkbit(a, n):
return a - pow2(n)
else:
return a + pow2(n)
end
Bitwise negation depends on how big your bitmasks are; specifically, the bitwise negative of an n-bit bitmask a is 2^n-1-a. If you're using 16 bits, it would be 65535-a.