The process of incorporating unsigned right shift for BigInt in JavaScript

I attempted the implementation provided in this answer, but unfortunately, it seems to be ineffective.

function urs32(n, amount) {
  const mask = (1 << (32 - amount)) - 1
  return (n >> amount) & mask
}

function flip32(n) {
  const mask = (1 << 32) - 1
  return ~n & mask
}

log(~0b10101010 >>> 0, urs32(~0b10101010, 0))
log(~0b10101010 >>> 0, flip32(0b10101010))

function log(a, b) {
  console.log(a.toString(2), b.toString(2))
}

In both scenarios, I would anticipate that a is equivalent to b, if executed correctly. Essentially, my objective is to invert 32-bits (turning '1's into '0's and vice versa). Despite noting that 1 << 32 === 0, using 2 ** 32 still doesn't produce the desired outcome.

How can one achieve the equivalent of ~n >>> 0 with a BigInt?

My aim is to develop the countLeadingOnes functions based on the existing countLeadingZeroes functions as illustrated below:

const LEADING_ZERO_BIT_TABLE = makeLeadingZeroTable()

function makeLeadingZeroTable() {
  let i = 0
  const table = new Uint8Array(256).fill(0)
  while (i < 256) {
    let count = 8
    let index = i
    while (index > 0) {
      index = (index / 2) | 0
      count--
    }
    table[i] = count
    i++
  }
  return table
}

function countLeadingZeroes32JS(n)
{
  let accum = LEADING_ZERO_BIT_TABLE[n >>> 24];

  if (accum === 8) {
    accum += LEADING_ZERO_BIT_TABLE[(n >>> 16)]
  }
  if (accum === 16) {
    accum += LEADING_ZERO_BIT_TABLE[(n >>>  8)]
  }
  if (accum === 24) {
    accum += LEADING_ZERO_BIT_TABLE[ n       ]
  }

  return accum;
}

function countLeadingZeroes16JS(n)
{
  let accum = LEADING_ZERO_BIT_TABLE[n >>> 8]

  if (accum === 8) {
    accum += LEADING_ZERO_BIT_TABLE[n]
  }

  return accum;
}

function countLeadingZeroes8JS(n)
{
  return LEADING_ZERO_BIT_TABLE[n]
}

console.log('countLeadingZeroes32JS', countLeadingZeroes32JS(0b10100010001000100010001000100010))
console.log('countLeadingZeroes32JS', countLeadingZeroes32JS(0b00100010001000100010001000100010))
console.log('countLeadingZeroes32JS', countLeadingZeroes32JS(0b00000010001000100010001000100010))
console.log('countLeadingZeroes16JS', countLeadingZeroes16JS(0b1010001000100010))
console.log('countLeadingZeroes16JS', countLeadingZeroes16JS(0b0010001000100010))
console.log('countLeadingZeroes16JS', countLeadingZeroes16JS(0b0000001000100010))
console.log('countLeadingZeroes16JS', countLeadingZeroes16JS(0b0000000000100010))
console.log('countLeadingZeroes8JS', countLeadingZeroes8JS(0b10100010))
console.log('countLeadingZeroes8JS', countLeadingZeroes8JS(0b00100010))
console.log('countLeadingZeroes8JS', countLeadingZeroes8JS(0b00000010))

function countLeadingOnes32JS(n) {
  return countLeadingZeroes32JS(~n >>> 0)
}

function countLeadingOnes16JS(n) {
  return countLeadingZeroes16JS(~n >>> 0)
}

function countLeadingOnes8JS(n) {  
  return countLeadingZeroes8JS(~n >>> 0)
}

console.log('countLeadingOnes32JS', countLeadingZeroes32JS(0b00100010001000100010001000100010))
console.log('countLeadingOnes32JS', countLeadingZeroes32JS(0b11100010001000100010001000100010))
console.log('countLeadingOnes32JS', countLeadingZeroes32JS(0b11111100001000100010001000100010))
console.log('countLeadingOnes16JS', countLeadingOnes16JS(0b0100001000100010))
console.log('countLeadingOnes16JS', countLeadingOnes16JS(0b1111110000100010))
console.log('countLeadingOnes16JS', countLeadingOnes16JS(0b1111111111000010))
console.log('countLeadingOnes8JS', countLeadingOnes8JS(0b01000010))
console.log('countLeadingOnes8JS', countLeadingOnes8JS(0b11000010))
console.log('countLeadingOnes8JS', countLeadingOnes8JS(0b11111100))

Unfortunately, it seems that ~n >>> 0 does not function properly with 32-bit integers. Is there a way to resolve this issue?

Answer №1

Is there a way to create an unsigned right shift for BigInt in JavaScript?

Unsigned right-shift can be challenging to define for integers of arbitrary size, so it's important to establish how you want it to behave before attempting to implement it.
Moreover, considering the context of this question, it may not even be necessary.

It seems like a and b should be equal in both scenarios

However, that assumption might not hold true as unsigned right-shift and bit flipping yield different outcomes.

I noticed that 1 << 32 === 0

In reality, 1 << 32 === 1. In JavaScript (similar to x86 CPUs), there is an implicit &31 operation on the shift amount. Hence, ... << 32 is equivalent to ... << 0.

How can one achieve the same effect as ~n >>> 0 with a BigInt?

The equivalent of ~n remains as ~n. Surprisingly, there is no direct shift involved in either the Number version or BigInt version, which might not address the original query regarding implementing USR for BigInt.

It appears that ~n >>> 0 doesn't function correctly with 32-bit integers.

On the contrary, it works exclusively with 32-bit integers.

Additionally, the >>> 0 component is superfluous and can be omitted without affecting the functionality.
Errors such as the incorrect output from countLeadingOnes32JS primarily stem from typos like calling ...Zeroes.... Handling 16-bit numbers within a 32-bit representation also poses challenges due to misinterpretation of data sizes. A potential fix involves applying a mask post-flip in functions like clo16:

function countLeadingOnes16(n) {
  return countLeadingZeroes16(~n & 0xFFFF);
}

No need for BigInts or >>> 0. Similar adjustments apply to countLeadingOnes8.


To gain insight into bitwise operations involving negative numbers, consider learning about two's complement notation or similar concepts.

Furthermore, enhancing your debugging skills using techniques like inserting console.log statements, debugger stepping, or console evaluations can greatly aid in identifying and rectifying code issues efficiently.


For other readers, utilizing built-in methods like Math.clz32 proves more effective than manual implementations of countLeadingZeros, especially since it compiles to machine instructions. For narrower widths, a simple subtraction method suffices:

function clz8(n) { return Math.clz32(n) - 24; }

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

Retrieve information from Django and pass it to the Vue template

I'm attempting to transfer information from Django into Vue template variables. views.py def index(request): myvar = 1 return render(request, 'index.html',{'myvar':myvar}) within index.html <span> {{ myvar }} </span& ...

Secure the data by encrypting it in the frontend before decrypting it in the

How can I achieve the highest level of security in this situation? I have experimented with using the same public key for all users to encrypt data transmitted over HTTPS to my backend automatically. However, individuals could potentially intercept and d ...

Storing a child in an existing object with Firebase and Angular 6

How can I save a new form to an existing list with the following code snippet: createNewTumeur(newTumeur: Tumeur) { this.tumeurs.push(newTumeur); const id: string = this.route.snapshot.params['id']; firebase. ...

Which is the better choice for implementing a singleton: let or var?

I have a clear understanding of the distinction between let (locks the reference inside the block) and var (declares a variable accessible scope-wide). When it comes to implementing the singleton pattern in a module-based setting: var singleton = null; m ...

Ways to conceal <td>s in angularjs on specific rows during ng-repeat

In the first <tr>, I have a table with many <td> elements that I am populating using ng-repeat. <tr ng-repeat="receipt in $data"> <td data-title="voucher number"> <span>{{receipt.voucher_no}}</span> </td ...

Discovering the closest date among the elements in an array

Currently, I am facing an issue while trying to identify the highest date within an array of objects which have varying dates assigned to each one. The code seems to be functioning well when the dates are above January 1st, 1970, however, any date prior to ...

What is the process for bundling a separate JavaScript file with Webpack5?

I am new to the world of webpack. I have 2 javascript files and I want to designate one as the main entry file. However, for the other file, I only want to include it in specific files. For example, looking at the file structure below, main.js is my entr ...

The `stream.Transform.unshift()` method in Node.js

Let's take a look at this simple example: stream = require 'stream' util = require 'util' class TestTransform extends stream.Transform _transform: (chunk, encoding, callback) -> if not @noMore @noMore ...

Activate html5 form validation when clicking on an asp.Net LinkButton using OnClientClick

I am working with a webform application Within the Master Page, I have created a form as follows: <body class="tile-1-bg"> <form id="form1" runat="server"> On my page.aspx file, the form includes the following elements: <div class="contr ...

ng-include: Child scope access problem

I am currently facing an issue with my app while using DayPilot Scheduler. home.html: <div class="container-fluid"> <daypilot-scheduler id="scheduler" daypilot-config="schedulerConfig" daypilot-events="events"></daypilot-scheduler> ...

What is causing TypeScript to compile and remove local variables in my Angular base controller?

I am trying to develop a base controller in Typescript/Angular for accessing form data, but I'm encountering an issue where the form member seems to be getting removed during compilation and is not present in the generated JavaScript code. Could you ...

The absence of a property map within String Flowtype has caused an issue

There is an issue with Flowtype when it comes to arrays. type Properties = { films?: Array<any> } render() { const { movies } = this.props; return ( <React.Fragment> <main className="moviedata-container"> { ...

The error message "Comparison between 'NoneType' and 'int' not possible in Django dynamically added forms" is indicating an issue with comparing instances of different data types

Currently in the process of developing a website using Django where users can input recipe details and save them. This involves allowing users to dynamically add form fields for ingredients and recipe steps. I've managed to implement functionality to ...

The issue of duplicate results appearing in the Wikipedia viewer persists even after conducting a second search

I have been working on a project to create a wiki viewer, but I've encountered an issue. Currently, I am utilizing the Wikipedia API. When a user enters a search query, they are presented with 5 possible articles (title and first sentence), and upon ...

Modifying button text with jQuery is not feasible

I'm facing a challenge with jQuery and I need the help of experienced wizards. I have a Squarespace page here: . However, changing the innerHTML of a button using jQuery seems to be escaping my grasp. My goal is to change the text in the "Add to car ...

Javascript functions correctly when the HTML file is opened locally, however, it encounters issues when accessed through an http-server

My HTML file includes an embedded web widget from tradingview.com with the following code: <!-- TradingView Widget BEGIN --> <span id="tradingview-copyright"><a ref="nofollow noopener" target="_blank" href="http://www.tradingview.com" style ...

Is there a more efficient method for writing my jQuery code that follows a step-by-step approach?

I have developed a step-by-step setup process that guides users through various sections. Instead of using separate pages for each step (like step1.php, step2.php, etc.), I have all the code contained in one page named setup.php. This is achieved by utiliz ...

Utilizing AngularJS and ADAL.JS to Define Resource ID (Audience)

Is there a way to utilize adal.js within AngularJS to obtain a bearer token for the audience https://management.azure.com through JavaScript? I have created a client application in Azure AD and configured its permissions to allow access to the "Windows Az ...

Issue encountered when attempting to retrieve elements within an HTA's IFrame

We are currently working on automating an Intranet site using HTA and JavaScript. To bypass the browser security settings, we have implemented an Iframe within the HTA itself instead of opening the site in a browser. Despite being able to successfully logi ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...