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!
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!
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)
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
};
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
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
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
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. ...
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 ...
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 ...
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 ...
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, ...
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= ...
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 ...
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 ...
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> ...
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 ...
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 = ...
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 ...
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 ...
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 ...
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 ...
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= ...
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 ...
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 ...
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 ...
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 ...