Can a calculation or estimation be made to determine the number of digits in a binary integer?

For example, in base 10(999) => 3 digits and in base 2(1111100111) => 10 digits

Currently, I am using a table to estimate this computation, but it is limited to 15 digits in base 10 because JavaScript is restricted by MAX_SAFE_INTEGER. Please refer to the following table (run snippet to view it).

How can we expand this table up to 255 digits in base 10 using a formula?

const TDigits   = document.querySelector('#T-Digits tbody')
,     MaxDigits = Number.MAX_SAFE_INTEGER.toString().length
;

var x9 = '9';

for (let n=1; n < MaxDigits; n++)
{
  let newRow = TDigits.insertRow(-1)

  newRow.insertCell(0).textContent = n
  newRow.insertCell(1).textContent = (x9-0).toString(2).length

  newRow.insertCell(2).textContent = Math.ceil(Math.log2(Math.pow(10,n)))
  
  x9 += '9';
}
table { margin:1em}
table thead { background-color: cadetblue }
table td { text-align: center; padding: .2em .5em; border-bottom: 1px solid grey }
<table id="T-Digits">
  <caption>Max digits corresponding</caption>
  <thead>
    <tr><td>base 10</td> <td>base 2</td><td> log </td></tr>
  </thead>
  <tbody>
      <tr><td>0</td> <td>1</td><td>1</td></tr>
  </tbody>
</table>

[edit] include Math.ceil(Math.log2(Math.pow(10,n))) from Jaromanda X, ;)

Answer â„–1

for (number = 1; number < 256; number +=1 ) {
    console.log(number, Math.ceil(Math.log2(Math.pow(10,number))));
}

Based on my analysis, the results are in agreement

Answer â„–2

 ⌊log2(n)⌋ + 1

let number = 123;
console.log(number, (number >>> 0).toString(2) );
let binaryNum = Math.floor( Math.log2(number) ) + 1;
console.log( binaryNum );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the errors in my subscription function?

Working on an e-commerce website, I encountered errors in the "cartservice" specifically in the "checkoutFromCart()" function. The console displayed the following error: src/app/services/cart.service.ts:218:81 218 this.http.post(${this.serverUrl}ord ...

Rows are not being displayed in JQgrid

Check out this JavaScript code: <script type="text/javascript> $(function () { $("#list").jqGrid({ url: "/Movies/GetAllMovies", datatype: "json", mtype: "GET", colNames: ["Id ...

Can you explain the purpose of IEventRepository in this snippet of code? Could you elaborate on what functionality is achieved by

public JsonResult FetchEvents(double start, double end) { var username = Session["Username"] as string; if(string.IsNullOrWhiteSpace(username)) { return null; // Return nothing if username is empty } var fromDate = ConvertF ...

What could be causing my Svelte store's subscribe() method to trigger despite no change in value?

One of the Svelte stores I am using is called activeAccountIndexStore: export const activeAccountIndexStore: Writable<number | "native" | null> = writable(null); Initially, the value of the store is null, but it gets set to either a spec ...

Errors encountered during global installation of Handlebars using `npm install`

Recently, I attempted to install handlebars.js through NPM in my terminal on OS X 10.9.3. Following the instructions provided at http://handlebarsjs.com/precompilation.html (I had to add a "." to avoid exceeding hyperlink limits due to lack of reputation) ...

Error: The function was not passed as a valid function

Currently, I am in the process of creating a concise 'Engine' class to streamline interactions with Three.js. I have restructured the Render() method from the example into this Engine JS class, as shown below: const Engine = function () { cons ...

Issue occurs when trying to access the 'set' property of an undefined variable, leading to an error message stating "Cannot read property 'set' of undefined" while using 'this

I'm facing an issue while setting up basic cookies for my Vue project. When I try to set a cookie, I encounter the following error. My package.json file indicates that I am using vue-cookies version ^1.7.4. The error message occurs when I click the bu ...

Tips for compressing an image in a React application with the help of react-dropzone

I have integrated the react dropzone package into my Next JS app and I am looking to add automatic image compression feature. After receiving the images, I converted the blob/preview into a file reader. Then, I utilized the compressorjs package for compre ...

Determining the angular difference between the direction of particle motion and a straight line

Currently, I am in the process of developing a simulation involving a bouncing ball. In this simulation, users have the ability to place lines on the canvas that the ball can collide with by dragging from one point to another. There are specifically four t ...

Decoding PDF417 Barcodes with ZXing.NET using HTML5 Video

I'm currently exploring the use of jQuery/JavaScript in conjunction with ZXing.NET to decode a PDF417 barcode from a video source. Below is the HTML I am working with: <video id="video" width="800" height="800"></video> <canvas id="ca ...

Is it possible to utilize PropTypes to indicate that a prop is of type Promise?

Using PropTypes can aid in debugging by providing warnings when expectations are not met. Additionally, they serve as a helpful tool to clearly express how a component should be used. If I have a component that requires a prop with a value that could pote ...

suggesting options comparable to addthis or sharethis

Could you please check out ? There is a sharing box in the bottom right corner that resembles ShareThis. However, as far as I know, ShareThis does not have options for embedding or submitting content. Does anyone happen to know which plugin is being used ...

What could be causing the discrepancy in the model value when using checkboxes in AngularJS?

Something strange is happening with my code. I have a checkbox in my view that has a directive to display its value when it changes. Surprisingly, it works fine in Firefox, showing the correct values. However, in other browsers like Chrome, it shows the op ...

Is it possible to verify the existence of several arrays of data in a MongoDB database using Node.js?

I'm trying to verify if certain data exists in a database. If the data does exist, I want to set the value of k to 1. global.k = 0 let roll = {roll0:"1616",roll1:"234"} for (let i = 0; i < inputcount; i++) { let obj1 = roll["roll" + i]; const ...

Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don& ...

Having trouble with the redirect feature back to the previous page?

After attempting to use windows.history.back() to return the user to the previous page and finding that it was not working, I tried using debugger which redirected the page successfully. However, without debugging in Firebug, the command did not work. I ...

Button choosing one "YES" and one "No" from options within a group

I attempted to develop a similar layout like this: The requirement is to only allow one "Yes" and one "No" option to be selected within each group, ensuring there are no consecutive selections in a row or column. https://i.sstatic.net/x1Td8.png I made a ...

Is it possible to swap out images using srcset attribute?

Currently, I am facing an issue regarding changing the img on mobile and tablet devices to display different images. As a beginner with jQuery, I couldn't resolve it using that framework, so I am exploring options with html5. I am wondering if there ...

Can you please explain what the $save() function within the $resource resource does and how it facilitates CRUD operations on server-side data

Do you have any doubts about Angular resource? Check out the documentation here. Let's consider this code snippet: var User = $resource('/user/:userId', {userId:'@id'}); User.get({userId:123}, function(user) { user.ab ...

Trigger the restart of a jQuery function once the condition within it is satisfied

I have a payment page with various payment options displayed. If the selected payment option is 10, a list of banks that support that payment option is shown. When a bank is clicked from the dropdown list, I generate a button with the corresponding paymen ...