0

Let's say we have a binary integer, which I'll call "A", like 101110101100100011. I want an efficient javascript function that makes the whole value partial (like the digits after a "."). So our function, which I'll call intToPart should return 0.101110101100100011 if we input "A".
My 1st idea is to do:

var A=191267 //our binary number in decimal. The computer will read it as "101110101100100011" when doing math.
function intToPart(myInt){
  var myNum=myInt.toString(2).length;
  return myInt/(1<<myNum);
}

Is their a much more efficient way of doing this, or is my way the best? My function returns the correct value, but I am not sure if there is some special way to bit shift it that is better.

1 Answers1

0

It should be more efficient because there's no call to toString.

var A = 191267 //our binary number in decimal. The computer will read it as "101110101100100011" when doing math.
function intToPart(myInt) {
    var myNum = 0, r = myInt;
    while (r!==0) { r >>= 1; myNum++ }
    return myInt / (1 << myNum);
}
console.log(intToPart(A))

or

var A = 191267 //our binary number in decimal. The computer will read it as "101110101100100011" when doing math.
function intToPart(myInt) {
    return myInt/(2**Math.ceil(Math.log2(myInt)));
}
console.log(intToPart(A))
8HoLoN
  • 1,122
  • 5
  • 14