HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Reversed Binary Numbers in JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptbinarynumbersreversed

Problem

I'm trying it out just to see if I could solve it. It would be great if I could receive tips on how to improve it.

//input
var decimal = prompt("Please enter a decimal number");
if (decimal >= 1 && decimal < 1000000000) {
    //convert to binary
    var binConvert = parseInt(decimal, 10).toString(2);

    //reverse binary number
    var makeString = binConvert.toString();
    var srj = makeString.split("").reverse().join("");
    var makeNumber = Number(srj);

    //convert back to decimal
    alert(parseInt(makeNumber, 2));

} else {
    alert("Input number should be: 1 <= N < 1 000 000 000. Please try again.");
}


jsFiddle

Solution

prompt("Please enter a decimal number");


is a little confusing to me. I thought you wanted a number with a few decimal digits on it.

It might make more sense to say "Please enter a base 10 number"

You are a little incosistent in how you turn your string numbers into number numbers.

In the beginning, you use parseInt:

var binConvert = parseInt(decimal, 10).toString(2);


In the end, you use parseInt:

alert(parseInt(makeNumber, 2));


But in the middle, you use Number:

var makeNumber = Number(srj);


It is better to be consistent and stick to one function (in my opinion, you should use parseInt).

If you take the above advice in using parseInt, you can then get rid of the last parseInt call like so:

var makeNumber = parseInt(srj, 2); // I moved the parseInt call up here

//convert back to decimal
alert(makeNumber);


This might just be me, but your comments are a little confusing.

Here, you wrote:

//convert back to decimal
alert(parseInt(makeNumber, 2));


Aren't you technically converting to binary? (The radix parameter of parseInt is 2).

Code Snippets

prompt("Please enter a decimal number");
var binConvert = parseInt(decimal, 10).toString(2);
alert(parseInt(makeNumber, 2));
var makeNumber = Number(srj);
var makeNumber = parseInt(srj, 2); // I moved the parseInt call up here

//convert back to decimal
alert(makeNumber);

Context

StackExchange Code Review Q#88709, answer score: 4

Revisions (0)

No revisions yet.