3

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.

asked Aug 30, 2014 at 8:39
1
  • 3
    The Wikipedia article on bitwise operations explains the mathematical equivalents, mostly they seem to be based on some modulo2 operations. Commented Aug 30, 2014 at 9:17

1 Answer 1

12

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.

answered Aug 30, 2014 at 9:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.