Steps to transform every character into binary code

I am facing an issue where I need to convert each character into a binary number based on a specific condition. Numbers greater than or equal to 5 should be converted to 1, while numbers less than or equal to 4 should be converted to 0.

Here is the entire code snippet:

n = [
  '0110100000', '1001011111',
  '1110001010', '0111010101',
  '0011100110', '1010011001',
  '1101100100', '1011010100',
  '1001100111', '1000011000'
] // array of binary 

let bin = [] // converting to numbers
length = n.length;
for (var i = 0; i < length; i++)
  bin.push(parseInt(n[i]));

var sum = 0; // sum of all binaries
for (var i = 0; i < bin.length; i++) {
  sum += bin[i];
}
console.log(sum); // 7466454644

// ...
// code converting each character
// ...

// console.log(sumConverted) // 1011010100

Is there a way for me to convert characters greater than or equal to 5 to 1 and those less than 5 to 0?

For example:

7466454644
7=1, 4=0, 6=1, 6=1, 4=0, 5=1, 4=0, 6=1, 4=0, 4=0
return 1011010100

Answer №1

In each iteration, the concept is to extract the last digit from the whole number using last_digit = number%10, then eliminate this last digit from the original number by performing number = Math.ceil(number/10). Repeat this process until the number reaches 0

For instance:

number = 123;
last_digit = 123%10 = 3
number = Math.ceil(number/10) = 12

let num = 7466454644;

let convertedBinary = '';
while (num) {
  const binary = (num % 10) < 5 ? 0 : 1;
  convertedBinary = `${binary}${convertedBinary}`;
  num = Math.floor(num/10);
}

console.log(convertedBinary);

May this explanation be of assistance!

Answer №2

Break down the number into individual digits using a string and iterate over them:

const sum = 628490795;

const digitsString = sum.toString(); // convert to string

const modifiedDigits = digitsString
    .split("")                 // separate each digit
    .map((digit) => +(+digit > 7))     // if a digit is greater than 7, turn it into 1
    .join("");                 // merge back into a string
    
console.log(modifiedDigits);           // 001100110

+(+digit > 7) may seem cryptic, but it is simply equal to Number(Number(digit) > 7). The aim is to transform a boolean value into either 0 or 1 by changing its type.

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

The tooltip being displayed is plain and lacks any design elements

When I hover over my a element, only a simple tooltip appears without any styling, unlike what is shown in the Bootstrap documentation. (I am creating the a element using JavaScript) HTML <!DOCTYPE html> <html lang="en"> <head> ...

Steps to store user input into an array and subsequently combine the stored input:

I am currently working on a form that consists of two text boxes: Task and Description. My goal is to be able to log the input from both boxes and save it via a submit button. For example: Task: do laundry Description: do a buttload of laundry (idk lol) I ...

Creating a smooth animated scroll to a specific #hash while keeping elements hidden on the page

I'm facing an issue with a JavaScript function that scrolls to a selected element with scroll animation. Everything is working fine, however, I encounter a problem when sliding up or down to show/hide certain elements. When a clicked link contains th ...

Can you share a method in javascript that extracts href= and title values, similar to PHP's preg_match_all() function?

I received an HTML string as :var code; I am looking to retrieve all the values of href and title similar to how it is done using PHP's preg_match_all(). I have achieved a similar task in PHP with the provided example but now I am curious about how I ...

How to obtain mouse coordinates on a texture using three.js

I am looking to develop an engaging interactive panorama similar to the one showcased here: However, I am interested in allowing users to have the ability to interact with it. Is it feasible to retrieve coordinates from the texture based on mouse movemen ...

Discovering the minimum and maximum values in a Java two-dimensional array

public class DataHandler { static Integer[][] data = new Integer[10][12]; static int x = 0, y = 0; static int number; public DataHandler() { try { BufferedReader reader = new BufferedReader(new FileRe ...

JSGrid not displaying any information from the JSON source

Hello! I'm currently working on customizing the "DataManipulation" example from jsGrid demos, but I'm facing a challenge in displaying data fetched from a JSON file using a GET AJAX call. Below is my controller code: { loadData: ...

Modifying fields in a dynamic Oracle APEX report

Not a beginner or an expert in Apex here, But, I have limited knowledge of major client-side web languages, and now I need to tackle them. And soon. Here is an example here - username : test, password : test. I am using the same jQuery and JavaScript ...

How to effectively manage the default API quota in YouTube Data API v3 while ensuring requests are made every 60 seconds

Recently, I've encountered a challenge concerning the management of the default API quota for YouTube Data API V3, which allows 10,000 daily requests. In my JavaScript application, I need to fetch the number of subscribers and concurrent viewers every ...

How can I eliminate the unexpected .parse error in the HTTP Request JSON?

For my school project, I am utilizing IBM Bluemix to develop a web service. The core of my project requires fetching a JSON from an API in order to utilize the provided data. My main challenge lies in the HTTP request to the API service, as I encounter t ...

Executing Continuous Process using Node.js

I am currently working on a server project that involves streaming webcam footage and other functionalities. Everything is set up within my node.js server, with an HTML page that includes a select drop-down menu linked to a JavaScript function via socket.i ...

I am seeking to showcase an image in a window, and upon the image being clicked, execute the code in a separate window

I am looking to showcase the image provided below. <img src="http://gfx.myview.com/MyView/skins/livesample/image/livesample.gif" alt="" border="0"><a/> Once the image is clicked, I want it to execute the following code. How can I ensure that ...

The Ion-button seems to be malfunctioning

I am interested in using special buttons for my ionic 1 project, specifically the ion-button feature outlined on this page: Ionic Buttons. I attempted to create a Round Button and an Outline + Round Button: <h2 class="sub-header" style="color:#4 ...

Tips for efficiently storing and managing large data volumes in real-time applications

I am currently developing a real-time collaborative canvas project. Users have the ability to create rooms and invite others to join with a specific ID and password. The application also supports multiple tabs and utilizes fabric.js for handling canvas ope ...

Angular 7: Finding the variance between array elements

How can I subtract the values from the first 3 rows of the table? The formula is TVA Collectée - TVA Déductible - TVA Déductible/immo If the result is positive, it should be displayed in the box labeled TVA à Payer. If it's negative, it should g ...

Creating variable assignments based on object properties

I am facing a dilemma with a simple object that contains constants. { KEY1: "value1", KEY2: "value2" } I am looking for a way to make these constants accessible globally. Currently, I have to use Config.KEY1 to access the values globally, but I w ...

Typescript code encountering unexpected behavior with Array.includes()

Below is a snippet of TypeScript code from my NextJS application: const holeSet:any[] = []; ..... let xx = 1, yy = 2; holeSet.push({x:xx,y:yy}); xx = 3; yy = 4; holeSet.push({x:xx,y:yy}); holeSet.map((e) => { console.log("element ::"+JSON ...

Problems with Web Audio API Implementation - struggling to make it functional

As a newcomer to the Web Audio API and not well-versed in JavaScript, I am trying to implement a specific function on a website that involves Google's TTS API. This function requires the returned Base64 audio to pass through a reverb filter and then a ...

When req.body is instantiated, Mongoose returns an empty object

Hello there! Invoice model contains a nested Item array, and I am creating a new Item object using the data from newItem.ejs. However, Mongoose is returning an empty object even though the request body is not empty. I would greatly appreciate any advice ...

What methods can be employed to execute a intricate substitution utilizing both javascript and jQuery?

Within the source code of my web pages, I have elements that resemble the following: <div id="opt_3" >A)</div> <div id="opt_2" >B)</div> <div id="opt_4" >C)</div> <div id="opt_5" >D)</div> <div id="op ...