Convert from binary to hexadecimal in shortest amout of code [duplicate] - javascript

This question already has answers here:
JavaScript: Need functions to convert a string containing binary to hex, then convert back to binary
(4 answers)
Closed 9 years ago.
What is the easiest way to do this in Javascript? Currently my code is a giant switch block, is there an easier way?
Current code:
function convertBintoHex(input){
input = ""+input;
while(input.length < 8){
input = "0" + input;
}
input = [input.substring(0,4),input.substring(4,8)];
var output = "";
for(var i in input){
switch(input[i]){
case "0000":
output += 0;
break;
case "0001":
output += 1;
break;
case "0010":
output += 2;
break;
case "0011":
output += 3;
break;
case "0100":
output += 4;
break;
case "0101":
output += 5;
break;
case "0110":
output += 6;
break;
case "0111":
output += 7;
break;
case "1000":
output += 8;
break;
case "1001":
output += 9;
break;
case "1010":
output += 'A';
break;
case "1011":
output += 'B';
break;
case "1100":
output += 'C';
break;
case '1101':
output += 'D';
break;
case '1110':
output += 'E';
break;
case '1111':
output += 'F';
break;
}
}
while(output.charAt(0) == 0 && output.length > 1){
output = output.substring(1);
}
return "0x" + output;
}

Using built-in functions:
parseInt('1010101010', 2).toString(16)

Related

how to use switch statment

im new with JS and i read about the switch statement. i dont know how to use it
i got an exercise to complete.
got an array with numbers 1-10 and the result need to be with words like "one","two","three"..
Thats what i got so far :
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(numbers) {
case "1":
text = "one";
break;
case "2":
text = "two";
break;
case "3":
text = "three";
break;
case "4":
text='four';
break;
case "5":
text = "five";
break;
case "6":
text = "six";
break;
case "7":
text = "seven";
break;
case "8":
text = "eight";
break;
case "9":
text = "nine";
break;
case "10":
text = "ten";
}
}
return text;
}
sayNum()
You could do it like this, for example:
function sayNum(){
let numbers = [1,2,3,4,5,6,7,8,9,10];
let result = [];
for(let i=0;i<numbers.length;i++) {
switch(numbers[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text = "four";
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
break;
}
result.push(text);
}
return result;
}
let namedNumbers = sayNum();
console.info(namedNumbers);
This will:
Add the textual values to an array, representing each number in the source array
Return the resulting array to the caller
Log the result in the console
In the switch statement, you pass an 'expression' into the switch statement. The expression itself can be a string, a number, float, boolean etc. Now, the expression is compared to each of the case clause. And this is a 'strict' comparison. And that is the reason why your code was not working.
Firstly you were passing an undeclared variable, 'numbers' as the switch expression. Instead, you should be passing the ith element of the nameNumber[i] array like so: switch(nameNumber[i]){ }
And, secondly, in each of your case clauses, you are comparing the value to a string like "1", "2". But the switch expression is compared using strict equality === operator, therefore when your nameNumber array contains numbers and not strings, your 'case' clauses should also have numbers and not strings. That means case 1: instead of case "1":.
You can read more about the switch-case here: Switch Statement
I have fixed your code below with the changes I mentioned above. Please run the below code snippet to see how it works. Goodluck!
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(nameNumber[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text='four';
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
}
console.log(text);
}
return text;
}
sayNum();
Rather than using a switch, use if statement. Because in switch, break statement can be used to jump out of a loop.
let text = '';
function sayNum() {
let nameNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < nameNumber.length; i++) {
if(nameNumber[i] == 1){
text += `"one",`;
}
if(nameNumber[i] == 2){
text += `"two",`;
}
if(nameNumber[i] == 3){
text += `"three",`;
}
if(nameNumber[i] == 4){
text += `"four",`;
}
if(nameNumber[i] == 5){
text += `"five",`;
}
if(nameNumber[i] == 6){
text += `"six",`;
}
if(nameNumber[i] == 7){
text += `"seven",`;
}
if(nameNumber[i] == 8){
text += `"eight",`;
}
if(nameNumber[i] == 9){
text += `"nine",`;
}
if(nameNumber[i] == 10){
text += `"ten"`;
}
}
}
sayNum();
console.log(text)

JS Split Varables

I have a String like "iyxnhel2jeh" and i want to for each 2 byte I want to split those into a single var.
var string = "iyxnhel2jehe";
var final = "";
while (/*String still has bits*/) {
switch (/*Two byte of string*/) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
}
Whats the best way to cut this string?
You could use regex to split string into 2letter parts, map them onto the characters from switch statement and join array back together, however the optimal way to do that would be to get rid of the switch statement and instead use those sequences of characters as keys of a object.
var string = "iyxnhel2jehe";
var final = string.match(/.{1,2}/g).map(twoletters => {
return {
"iy": "x",
"xn": "o",
"he": "g",
"l2": "k",
"je": "e"
}[twoletters] || "none";
}).join("");
console.log(final)
I'm not sure about the best way, but the following would do what you want...
var string = "iyxnhel2jehe";
var final = "";
for (var i = 0; i < string.length; i+=2) {
switch (string.substr(i,2)) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
}
console.log(final);
var string = "iyxnhel2jehe";
var final = "";
var offset = 0;
while (offset < string.length) {
switch (string.slice(offset, offset + 2)) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
offset += 2;
}
console.log(final);
Instead of trying to consume characters and check whether there are still any left, try splitting the string into 2-character chunks first, and loop through the array:
const s = "iyxnhel2jehe";
let final = "";
const t = s.split('');
const segments = t.map((e, i) => i % 2 === 0 ?
e + (t.length - 1 >= i + 1 ? t[i + 1] : '') :
null)
.filter(x => x != null);
segments.forEach(sg => {
console.log(sg);
switch (sg) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
});
console.log(final);

Is there a way to name the same case but when is 2 times clicked?

I'm translating some interactives for a math school from English to Spanish. I'm having problems adapting the code to numbers in Spanish.
So I'm doing cases to change the order and the text (the numbers in Spanish have a different form to write between 20 and 24) in the console log the case "veinte" works to 20 but when you go 22 the case "veinte" count like 2 times "veinte" case. (see the image below)
I don't know how to make a x2 of the same case. Sorry if I don't know how to make a good explanation of my problem, it's kind of confusing.
for(i = 0 ; i < q.length ; i++)
{
if(q[i] != null)
{
if(LowerCase)
q[i] = q[i].toLowerCase();
switch((3 - q.length) + i)
{
case 0:
switch(q[i]){
case 'Cinco':
q[i] = 'Quinientos';
break;
case 'Siete':
q[i] = 'Setecientos';
break;
case 'Nueve':
q[i] = 'Novecientos'
break;
case 'Uno':
q[i] = 'Cien'
break;
default:
q[i] = q[i] + "cientos";
}
vTemp = o.substring(i + 1);
if(parseInt(vTemp) > 0)
//q[i] = q[i] + " and";
q[i] = q[i] + "";
break;
case 1:
switch(q[i]){
case 'veinte':
q[i] = 'veinti';
break;
default:
q[i] = q[i];
}
if((q[2] != null) && (q[2] != "x"))
q[i] = q[i] + " y";
break;
case 2:
if(q[i] == "x")
q[i] = "";
break;
}
LowerCase = true;
}
else
{
q[i] = "";
}
}

Javascript operators in switch case

I'm creating a panel and there are stats for memory, CPU and HDD. I'm using a switch statement and in the case method, I'm putting the current usage of CPU, memory and HDD.
However, the problem is that I'm using operators and I don't know which operator to use because I've tried all of them and I didn't get the results that I expected.
And this is the code: https://pastebin.com/YaxCm0Be
switch(true){
case (mem_percent_get <= 0.01):
var mem_progress_color = 'progress-bar-primary';
break;
case (mem_percent_get <= 33):
var mem_progress_color = 'progress-bar-success';
break;
case (mem_percent_get <= 66):
var mem_progress_color = 'progress-bar-warning';
break;
case (mem_percent_get <= 80):
var mem_progress_color = 'progress-bar-danger';
break;
default:
mem_progress_color = 'progress-bar-theme';
}
switch(true){
case (cpu_percent_get <= 33):
var cpu_progress_color = 'progress-bar-success';
break;
case (cpu_percent_get <= 66):
var cpu_progress_color = 'progress-bar-warning';
break;
case (cpu_percent_get <= 80):
var cpu_progress_color = 'progress-bar-danger';
break;
default:
cpu_progress_color = 'progress-bar-primary';
}
switch(true){
case hdd_percent_get <= 0.01:
var hdd_progress_color = 'progress-bar-primary';
break;
case hdd_percent_get <= 30:
var hdd_progress_color = 'progress-bar-success';
break;
case hdd_percent_get <= 60:
var hdd_progress_color = 'progress-bar-warning';
break;
case hdd_percent_get <= 80:
var hdd_progress_color = 'progress-bar-danger';
break;
default:
hdd_progress_color = 'progress-bar-theme';
}
Well, my first comment is to not use a switch in this case. What you are doing is essentially if () { } else if() {} blocks. You should be using switch when you have a value that you want to strictly check against. I suggest looking into at the MDN docs for switch.
Secondly, from what I can gather is that for the memory, you need it to be red when the value is 1696 / 2098 (80.83%). All of your if/elseif cases rely on <= which would mean that the value must be less than or equal to the number on the right of the equation. In your case, you are looking for <= 80, and without seeing how you calculate mem_percent_get (if it is in the pastebin, I'm unable to open that on my current network), you're value is likely above 80.
For your danger, you likely want 80-100+% as being red, so you should be using >= or greater than or equal to operator.
MDN has an excellent resources on comparison operators.
Created a getClassName method that accepts a percent and will return a className:
const getClassName = percent => {
switch(true){
case (percent <= 0.01):
return 'progress-bar-primary';
case (percent <= 33):
return 'progress-bar-success';
case (percent <= 66):
return 'progress-bar-warning';
case (percent <= 80):
return 'progress-bar-danger';
default:
return 'progress-bar-theme';
}
}
console.log('0: ', getClassName(0));
console.log('40: ', getClassName(40));
console.log('50: ', getClassName(50));
console.log('80: ', getClassName(80));
console.log('100: ', getClassName(100));

Can't concatenate a string in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to make a calculator with javascript. My code below takes the button clicks and adds them all together as a string. When the user presses the sum or equals button, the function is supposed to evaluate the string as an equation and log a result. for example result == "2 * 10" should return 20. My problem is that instead of doing that it just adds it together rather than multiplying or doing any other function like - or divide.
here is my code:
var result = 0;
function calc(digit){
if (digit == "sum"){
console.log(eval(result)) ;
}
else if (digit == "-"){
result + "-";
}
else if (digit == "+"){
result + "+";
}
else if (digit == "*"){
result + "*";
}
else if (digit == "/"){
result + "/";
}
else if (digit == "."){
result + ".";
}
else if (digit == "clear"){
location.reload();
}
else{
result += parseFloat(digit);
}
}
and here is an example of a button click for each function:
<button class="large" type="button" value="divide"onclick=calc("/")>/</button>
You need to use assignment operators for this.
For example, instead of result + "-", use result += "-". You had the right idea in your else block.
Anyways, since your code has multiple if/else conditionals, it would be better to use a switch statement
function calc(digit){
switch(digit) {
case: "sum":
console.log(eval(result));
break;
case "-":
result += "-";
break;
case "+":
result += "+";
break;
case: "*":
result += "*";
break;
case: "/":
result += "/";
break;
case: ".":
result += ".";
break;
case "clear":
location.reload();
break;
default:
result += parseFloat(digit);
}
}
Here's some more information on String Concatenation in JavaScript
http://www.w3schools.com/jsref/jsref_concat_string.asp
In your if stack, result + "-" doesn't do anything. To add the minus sign to the end of result, you would do something such as
result = result + "-";
or
result += "-";
Currently, result + "-" has the system do the concatenation of result and the string, but immediately loses it because you didn't store it back in result.

Categories