Changing a "boolean bit array" to a numerical value using Typescript

Asking for help with converting a "boolean bit array" to a number:

const array: boolean[] = [false, true, false, true]; // 0101

Any ideas on how to achieve the number 5 from this? Appreciate any suggestions. Thanks!

Answer №1

I am not familiar with TS, but in pure JS, you can achieve the following:

a = [false, true, false, true]
b = a.reduce((res, x) => res << 1 | x)
alert(b)

If you want to go from number to array:

b = 5
a = b ? [] : [false]

while(b) {
  a.push((b &1) === 1)
  b >>= 1
}

alert(a)

Alternatively,

b = 5

a = b.toString(2).split('').map(x => x === '1');

alert(a)

Answer №2

This code snippet is compatible with TypeScript.

async convertBoolToInt(boolArray:boolean[]){
    let debugMode = true;
    if(debugMode){
        console.log('Debug : "convertBoolToInt" Started');
        console.log('boolArray = ' + boolArray);
    }
    let bitArray:number[] = [];
    boolArray.forEach((element) => {
        bitArray.push(+element);    //convert boolean to bit
    });
    if(debugMode){
        console.log('bitArray = ' + bitArray);
    }
    let result: any = bitArray.reduce((accumulator: number, currentValue: number) => accumulator << 1 | currentValue); //perform bitwise conversion to integer
    if(debugMode){
        console.log('result = ' + result);
        console.log('Debug : "convertBoolToInt" Finished');
    }
    return result
};

Answer №3

To achieve this task, I recommend using a simple approach of converting numbers to binary and using string split/join functions.

const convertToBinary = (num: number): Array<boolean> => (num).toString(2).split('').map(bit => bit === '1')
const convertToNumber = (arr: Array<boolean>): number =>
    parseInt(arr.map(bit => bit ? '1' : '0').join(''), 2)

By utilizing the convertToNumber function, you can test it by checking:

console.log(convertToNumber([false, true, false, true])) // 5

Answer №4

Explores the concept of representing an array of boolean values as a number and vice versa, even though it does not directly answer the initial question.

const boolsToNum = (bools: boolean[]) => { 
    return bools.reduceRight((res, bool) => res << 1 | +bool, 1)
}
const numToBools = (num: number) => {
    const bools = []
    while (num > 1) {
        bools.push((num & 1) === 1)
        num >>= 1
    }
    return bools
}

The use of reduceRight() instead of reduce() eliminates the need for reversing the array when converting back to bools. By setting the initial value to 1 instead of 0, the array size is preserved and starts with false values. This approach emulates having an additional true value at the beginning of the array, saving the need to check the array length later on. The extra bit is disregarded during conversion back using while (num > 1).

const array:Array<boolean> = [false, true, false, true]; // 0101

console.log(array, 'original')
const num = boolsToNum(array)

console.log(num, 'compressed')
console.log(numToBools(num), 'uncompressed')

// (4) [false, true, false, true] original
// 26 compressed
// (4) [false, true, false, true] uncompressed

Answer №5

Implement a simple approach

function binaryArrayToNumber(arr) {
  let result = 0;
  for (let index = 0; index < arr.length; index++) {
    if (arr[arr.length - index - 1]) {
      result += 2 ** index;
    }
  }
  return result;
}

console.log(binaryArrayToNumber([true, false, true])); // 5

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 is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

Trouble with displaying ChartsJS Legend in Angular11

Despite thoroughly researching various documentation and Stack Overflow posts on the topic, I'm still encountering an odd issue. The problem is that the Legend for ChartsJS (the regular JavaScript library, not the Angular-specific one) isn't appe ...

Encountering issues with proper function of history.listen within React Router

I am struggling to get my function to work every time React detects a change in the URL. The history.listen method is not triggering (the console.log statement is not showing up). I have read that this issue may be related to using BrowserRouter, but when ...

Step-by-step guide on how to change the appearance of a <DIV> using data from a database (JSON

After retrieving data from a database as a JSON file, I have written code to loop through an item (portOn) and determine if certain ports are present in the array. If a port is found in the array, its corresponding variable is set to true. var portG01,port ...

Enigmatic void appears above row upon removal of content from a single item

When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it. I have found that using flexbox could solve this issue, ...

Next.js Head component will not repeat the same Meta Tags

In my Next.js project, I have implemented different meta tags with various media targets in the Head section: <Head> <meta name="theme-color" media="(prefers-color-scheme: light)" content="#7f8fa6"/> <meta name= ...

Node.js causing issues with retrieving data from REST Calls

I am trying to make a REST API call from my PHP and Node.js application to a specific URL provided by the client, which is expected to return a JSON object. While I am able to successfully retrieve data using PHP, I'm encountering issues with my Node ...

Mongoose fails to carry out internal query using Promise mechanism

Just diving into the asynchronous and await world, I decided to play around with Mongoose + MongoDB + Node.JS. Here is a snippet of my code: exports.updateBrandPreferences = async (req,res) => { var userID = req.body.playerID; var newBrands = r ...

Reading an XML file to locate items nested within the same bracket

Within my JavaScript function, I am utilizing the following code to extract data from an XML file: var title = $(this).children('Title').text(); This snippet of code successfully retrieves the content under the <Title> tags: <Title> ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

Managing promises with mongoose - Best practices

I am new to using mongoose and I am trying to figure out how to save and handle promises in Node.js using a mongoose schema. In the example below, I am attempting to save data to a collection and handle any errors that may occur. model.js var mongoose = ...

Modifying all occurrences of a specified string in an object (or array) - JavaScript

Is there a more efficient way to search through and replace all instances of a given string in a JavaScript object with unknown depth and properties? Check out this method, but is it the most optimal solution? var obj = { 'a' : 'The foo ...

Combining various datasets with identical X values in a D3 bar graph

I'm currently working on creating a grouped bar chart to display performance test results using D3 for the first time. The X axis should represent parallelism, indicating the number of threads used, while the Y axis will show the duration in millisec ...

Tips for achieving a background animation similar to the one shown on this page

Check out this link: danielcoding.me/resume/#contact I am interested in this animation: screenshot I tried inspecting element on the page, but couldn't find any background images. How can I create this animation? Is it achieved through JavaScript or ...

ReactJs: Tweaking Padding in Material-UI Table

After inheriting this fullstack app, I noticed that the original developers had incorporated a component to generate tables for the webpage. However, there is an issue with the padding on all the cells being too large. Through Chrome developer tools, I di ...

Having trouble with the JSON format within the 'operations' field in the formData of your Next.js application?

I encountered a mutation that looks like this- mutation signUp($avatar: Upload!) { signUp( avatar: $avatar input: { name: "Siam Ahnaf" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

What is the best way to emphasize a div depending on a query outcome?

A new application is in the works for a gaming project. This app is designed to display the location of a specific monster, utilizing a database containing information about monsters and their corresponding maps. Currently, the application functions almos ...

What is the best method to access the query string or URL within an AJAX page?

I recently discovered how to extract query string parameters from this helpful resource. However, I am facing difficulty retrieving the URL within the requested page via ajax. For instance: <div class="result"></div> <script> $(func ...

Flexbox helps create responsive layouts with ease

Utilizing flex to centrally position my element within my layers has worked well for me, but I encountered an issue when switching to a smaller screen size. The element simply scales down in size instead of taking up the full width like it does with Bootst ...

How can I apply JavaScript to aggregate child node values and assign them to the parent in JSON data format?

I receive a dynamic JSON from the server, which has varying structures. Each data entry consists of a chapter with stages and/or review sets at the root level. If a stage exists, there will be either a review set array or another stage. The review set cont ...