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

Looking at int 44 - I need Math.CEIL (log(2) 44)binary places to represent 44. (answer 6 places)

6 places:

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

But how can I verify that (for example) a bit is 8checked or not?

A simple solution would be to do:

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

But note that behind the scenes the computer translates 44into its binary representation and just checks to see if the bit is set in a bit-wise way.

Another solution is to simply create a binary file through toString(2)or mod%2in a loop

Question

Mathematically Through what formula can I check if a bit is set n'th?

(I would prefer an operation without a loop, but just one math phrase)

+4
3

"" ( ) val

val = 1966;
index = 2;
base = 10;
alert (Math.floor(val/Math.pow(base,index)) % base);

: 9

val = 44;
index = 3;
base = 2;
alert (Math.floor(val/Math.pow(base,index)) % base);

: 1 ( 0 1 - 0..base-1).

Math.floor ( Javascript) Math.pow . Math.pow "" . , :

alert (Math.floor(0.1+val/Math.pow(base,index)) % base);
+3

, , ( x mod 2 == 1)

:

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

JS:

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

: 0 (, 1)

+2

You can simply check if the value is set bitin the position 1.

function isBitSet(no, index) {
    var bin = no.toString(2);
    // Convert to Binary

    index = bin.length - index;
    // Reverse the index, start from right to left

    return bin[index] == 1;
}
isBitSet(44, 2); // Check if second bit is set from left

Demo

0
source

All Articles