Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check that a bit is set (without bitwise operation)?

Looking at the int 44 — I need Math.CEIL (log(2) 44) of binary places to represent 44. (answer is 6 places)

6 places :

___  ___  ___  ___  ___   ___
32   16    8    4    2     1

But how can I check that (for example) the bit of 8 is checked or not ?

A simple solution will be do to :

((1<<3) & 44)>0 so this will check if the bit is set.

But please notice that behind the scenes the computer translates 44 to its binary representation and just check if bit is set via bitwise operation.

Another solution is just to build the binary myself via toString(2) or mod%2 in a loop

Question

Mathematically Via which formula, I can test if n'th bit is set ?

(I would prefer a non loop operation but pure single math phrase)

like image 901
Royi Namir Avatar asked Jul 06 '15 08:07

Royi Namir


People also ask

How do you perform bitwise NOT operation?

Bitwise NOT (~)The 32-bit signed integer operand is inverted according to two's complement. That is, the presence of the most significant bit is used to express negative integers. Bitwise NOTing any number x yields -(x + 1) . For example, ~-5 yields 4 .

How do you identify a Bitwise operator?

Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.


1 Answers

Divide by the value of the bit that you want to check and test if the first bit is set (this can be tested with x mod 2 == 1)

Math expression:

floor(value/(2^bitPos)) mod 2 = 1

As JS function:

function isSet(value, bitPos) {
   var result =   Math.floor(value / Math.pow(2, bitPos)) % 2;
   return result == 1;
}

Note: bitPos starts with 0 (bit representing the nr 1)

like image 95
davidgiga1993 Avatar answered Oct 04 '22 15:10

davidgiga1993