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

Auto Suggest: How can I display all the attributes from a JSON object in the options list using material-ui (@mui) and emphasize the corresponding text in the selected option?

Currently, I am facing a requirement where I need to display both the name and email address in the options list. However, at the moment, I am only able to render one parameter. How can I modify my code to render all the options with both name and email? ...

Tips for parsing CSV files using d3 version 4

I'm currently grappling with the documentation for CSV Parse in D3. My code snippet looks like this: d3.parse("data.csv",function(data){ salesData = data; }); Unfortunately, I keep encountering this error: Uncaught TypeError: d3.parse is n ...

I encountered an issue where TypeScript's generics function was unable to locate a property within an interface

I am attempting to define a function in typescript using generics, but I encountered the following error: "Property 'id' does not exist on type 'CustomerInterface'" This occurs at: customer.id === +id getCustomer<Custo ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...

Executing a function while adjusting a range slider

Having an <input type="range"> element on my website presents a particular challenge. To handle changes in this element, I am using the following function: $("#selector").bind("change", function() { //perform desire ...

Rendering in Three JS involves efficiently utilizing one buffer to display the output within itself

I have been struggling with a particular issue and I really need some assistance: In my three js context, I have created a custom material and rendered it into a texture. ` /* Rendering in texture */ fbo_renderer_scene = new THREE.Scene(); fbo_r ...

Getting map data from Mapbox and displaying it on an HTML page

I have been working with Mapbox GL JS and successfully retrieved data in the console. However, I am facing issues when trying to display this data on an HTML page. Can anyone assist me with this problem? I specifically need the data inside mapdata to be sh ...

Is there a way to create a JavaScript function that relies on a successful form submission?

After attempting to modify a post on Stack Overflow, I am facing issues with my JavaScript code. As a beginner, it's possible that I overlooked something in the code causing it not to work as expected. The project I'm working on involves creatin ...

Continuously looping through the function based on availability in Symbol ES6

When using the ES6 Symbols iterator, I found that I needed to call the next function each time to print the next item during iteration. Below is the code snippet: var title = "Omkar"; var iterateIt = console.log(typeof title[Symbol.iterator]); var iter ...

Flask Session Persistence Issue: Postman Successful, Javascript Fails

Developing a Flask server to facilitate communication between backend Python functionality and Javascript clients on the web has been my recent project. I am trying to harness Flask's `session` variable to retain user-specific data throughout their in ...

When using the async pipe with Angular's ngFor, an error message indicates that the argument is

Can you explain why this error message is appearing: Argument of type '[string, { startTime: string; endTime: string; }][] | null' is not assignable to parameter of type 'Collection<unknown>'. It occurs when attempting to utilize ...

JavaScript opacity adjustments not achieving desired outcome

My attempt to make this sub menu fade in and out upon button press is not working as expected. It should fully fade in shortly after clicking 'help' and completely fade out when clicking 'back'. Is the problem with the method I'm u ...

Having identical functions with varying IDs and the same variable in Ajax is causing issues

Here, I have two HTML rows with different IDs. When the function ItemSearch() is called, I want to display the search results for both IDs. I am new to JavaScript and AJAX. ***1st Html*** <div class="justlauchSearch"> <div class="input-gro ...

Excellent JavaScript library for capturing screenshots of the entire screen

Is there a good JavaScript library that enables users to take a screenshot of a webpage and customize the size before saving it to their computer? I am specifically looking for a pure JS solution where users can simply click on a button and have a "save a ...

The peculiar characteristics of the dragLeave event in various web browsers

I observed a peculiar behavior while working with drag events in Internet Explorer 11. It seems that adding a 'width' property to the elements triggers the dragLeave event, whereas without it, the event does not fire. Can anyone shed light on why ...

Conditionally defining variables in JavaScript only if they are currently undefined

I have been working on extracting two keywords from a URL in the following format: localhost:3000/"charactername"/"realmname" My goal is to extract "charactername" and "realmname" and assign them to variables. Here is the code snippet I am using: var c ...

What is the best way to import API Endpoints from various directories in an Express Server?

I have been using a script to load my API endpoints like this: readdirSync('./routes/api').map((r) => app.use( `/api/v1/${r.split('.')[0]}`, require(`./routes/api/${r.split('.')[0]}`) ) ); This script reads eve ...

What exactly is a doclet as defined in JSDoc documentation?

//Sample 1 /** * Here we have a simple function that returns a message * @param {String} msg The message to be returned * @returns {String} The message */ function showMessage(msg) { return msg } //Sample 2 /** * This is a function that also retur ...

Retrieving data from a backend express server using Client-side Javascript

I have created an Express Server set up in the following way: var mysql = require('mysql2'); var express = require('express'); var app = express(); var PORT = 3000; app.get('/getDataFromDatabase', function(req, res) { cons ...

Tips for navigating a dynamic viewport using scroll movement

Attempting to create a responsive page with two distinct sections at this example link including: Map View Table View Both of these views (table and map divs) need to be responsive without a hard-coded height, so the size of the map div adjusts automatic ...