Can anyone explain this process with converting decimal numbers to Binary - javascript

I have looked around the internet for a way to convert decimal numbers into binary numbers. and i found this piece of code in some forum.
var number = prompt("Type a number!") //Asks user to input a number
var converted = []; // creates an array with nothing in it
while(number>=1) { //While the number the user typed is over or equal to 1 its shoud loop
converted.unshift(number%2); // takes the "number" and see if you can divid it by 2 and if theres any rest it puts a "1" otherwise "0"
number = Math.floor(number/2); // Divides the number by 2, then starts over again
}
console.log(converted)
I'm not understanding everything completely, so i made some comments of what i think the pieces of code do. But anyone that can explain in more detail? or is the way i think the code does correct?

This code is based on a technique for converting decimal numbers to binary.
If I take a decimal number. I divide it by two and get the remainder which will either be 0 or 1. Once you divide 57 all the way down to 0. You get the binary number for example:
57 / 2 = 28 r 1; 28 / 2 = 14 r 0; 14 / 2 = 7 r 0; 7 / 2 = 3 r 1; 3 / 2 = 1 r 1; 1 / 2 = 0 r 1;
The remainders are the binary number. Sorry if it's a bit hard to read. I definitely recommend writing it out on paper. Read from the last remainder to the first, the remainders look like this: 111001
Reverse it to make it correct. array.unshift() can do this or you could use array.push() then array.reverse() after the while loop. Unshift() is probably a better approach.
57 in decimal is equal to 111001, which you can check.
BTW, this algorithm works for other bases, as long you are converting from decimal. Or at least as far as I know.
I hope this helped.

It seems like you've got the gist of it down.
Let's start with a random number:
6 === 110b
Now let's see what the above method does:
The number is geq than 1, hence, let's add the last bit of the number to the output
6%2 === 0 //output [0]
the number we're working with after dividing the number by two, which is essentially just bit-shifting the whole thing to the right is now 11b (from the original 110b). 11b === 3, as you'd expect.
You can alternatively think of number % 2 as a bit-wise AND operation (number & 1):
110
& 1
-----
0
The rest of the loop simply carries the same operation out as long as needed: find the last bit of the current state, add it to the output, shift the current state.

Related

Please help make Modulo Simple To Understand

(Sorry in advance if this has been asked before, I searched and couldn't find a similar question)
So I believe modulo (%) gives me the remainder of a long division equation. so 2%4 =0r.
So in simple terms a modulo equation that equals zero should be an even number. and a modulo equation that equals 1, should be an odd number? Is that correct?
Here's where I begin to confuse myself.
What about equations that equal an even or odd remainder, would that still output an equal or odd number.
For instance. 5%149 equals 4r.. the remainder is an even number, so is the output all even numbers.. or does the very fact that there is any remainder at all mean that the output will be odd numbers??
TLDR, is modulo as simple as 0r outputs even numbers. And anything with 1 or more remainder outputs odd numbers.
Modulo (or modulus) is used to see the remainder of a division.
You can flip it on it's head and use multiplication to help you out as well if necessary. I've provided some examples.
Try doing something like this:
From the equation you posted in your example: 149 % 5 would give you the remainder of 4. Reason for this: The last multiple of 5 you can get before 149 is 145, and your modulus equation is telling you that you have 4 left over.
Now, if you were to do something like 150 % 5, your remainder would be 0 because 150 is a safe multiple of 5.
Some documentation should hopefully help you understand this a bit better as well: https://docs.onux.com/en-US/Developers/JavaScript-PP/Language/Reference/Expressions/arithmetic-operators/modulus
Some examples to help you understand the remainder:
10 % 5 = 0 Since 5 x 2 = 10
9 % 3 = 0 Since 9 x 3 = 9
6 % 2 = 0 Since 2 x 3 = 6
7 % 2 = 1 Since you can only multiply 2 three times to get 6, you are left with a remainder of 1.
a modulo equation that equals zero should be an even number. and a
modulo equation that equals 1, should be an odd number?
You've probably seen modulo as a way of testing for evenness but this is not right. It should read
a modulo by 2 operation that equals zero is an even number
ie. x % 2 == 0 implies x is even. Because x is divisible by 2. x % 3 == 0 means x is divisible by 3.
Here's one way I learned to look at it. Consider an analogue clock with n hours on in (perhaps n=12 or n=24 or some other funny clock). The first number in the modulo operation tells you how many hours forward to traverse, going round and round the circle. The second number (n) tells you how many hours is built into the clock.
Here are some examples:
You go forward 5 on a 12 hour clock and land on 5 o'clock.
5 % 12 == 5
You go forward 13, completing one full loop plus one more hour, landing on 1 o'clock.
13 % 12 == 1
You go forward 24, completing 2 full loops but landing at the starting point, 0. (ok most clocks have 12 at the top but its the same as 0.)
24 % 12 == 0
Consider a clock or spinning wheel with 4 categories.
Start at the base and take 7 steps forward. That give you one full traversal (4 steps) then 3 more steps lands you on the 3rd item.
7 % 4 == 3
You've just stepped forward 2. Because the wheel has 4 slots, the counting hasn't reset yet.
2 % 4 == 2
So to recap, the first number is the number of steps to take, the second number is the size of the clock.

Getting least significant bit in JavaScript

I am trying to get the least significant bit of a number in JavaScript.
I have the following code:
let lsb = (parseInt("110", 2) & 0xffff);
By my understanding, the least significant bit of 110 is 110 as it is the right-most set bit.
However, the code above returns '6', which is the total value of 110 and not the least significant bit.
How can I get the least significant bit?
I take you at your example that you are looking for the lowest set bit, not the least significant bit
What you're looking for is a bit of a bitwise hack.
We can do this with some exploitation of the way negative numbers are represented (two's complement)
var lowestSetBit = (value) & (-value)
If you are actually looking for the least significant bit, then you can just mask on that bit
var leastSignificantBit = value & 1
The least significant bit is the rightmost bit, not the rightmost bit that's set. To get that, AND with 1.
let lsb = parseInt("110", 2) & 1;
https://en.wikipedia.org/wiki/Least_significant_bit:
least significant bit (LSB) is the bit position in a binary integer
giving the units value, that is, determining whether the number is
even or odd
So it's easy:
let lsb = parseInt("110", 2) & 1
or even this:
let lsb = parseInt("110", 2) % 2
Finding the least significant bit of a number can easily be done by:
someNumber & 1
or in your specific case:
let lsb = (parseInt("110", 2) & 1
This works by masking every bit with a zero except for the least significant bit, which is &'d with that 1.
For example, let's have our input number be 21
21 & 1
Is the same as:
10101
& 00001
-------
00001 // => returns 1 since the last bit is turned on

Using bitwise operators in javascript

I am creating a bitmask in javascript. It works fine for bit 0 through 14. When I set only bit fifteen to 1. It yields the integer value of "-2147483648" instead of "2147483648". I can do a special case hack here by returning hardcoded "2147483648" for bit fifteen but I would like to know the correct way of doing it.
Sample code:
function join_bitmap(hex_lower_word, hex_upper_word)
{
var lower_word = parseInt(hex_lower_word, 16);
var upper_word = parseInt(hex_upper_word, 16);
return (0x00000000ffffffff & ((upper_word<<16) | lower_word));
}
Above code returns -2147483648 when hex_lower_word is "0x0" and hex_upper_word is "0x8000" instead of 2147483648
The reason for this is because Javascript's bit shift operations use signed 32-bit integers. So if you do this:
0x1 << 31 // sets the 15th bit of the high word
It will set the sign bit to 1, which means negative.
On the other hand instead of bit shifting you multiply by powers of two, you'll get the result you want:
1 * Math.pow(2, 31)
The reason is, you are setting the sign bit...
2147483648 is 1 followed by 31 zeros in binary...
As you are doing a bitwise operation, the output is always a signed 32 bit number, which makes the 32nd bit the sign bit, so you get a negative number...
Update
(upper_word * Math.pow(2, 16))
will give positive 2147483648.
But, you still have the OR operation, which puts us back to square one...
As previous answers explained, the bitwise operators are 32 bit signed. Thus, if at any point along the way you set bit 31, things will go badly wrong.
In your code, the expression
(upper_word<<16) | lower_word)
is evaluated first because of the parentheses, and since upper_word has the top bit set, you will now have a negative number (0x80000000 = -2147483648)
The solution is to make sure that you do not shift a 1into bit 31 - so you have to set bit 15 of the upper word to zero before shifting:
mask15 = 0x7fff;
((upper_word&mask15)<<16|lower_word)
This will take care of "numbers that are too big become negative", but it won't solve the problem completely - it will just give the wrong answer! To get back to the right answer, you need to set bit 31 in the answer, iff bit 15 was set in upper_word:
bit15 = 0x8000;
bit31 = 0x80000000;
answer = answer + (upper_word & bit15)?bit31:0;
The rewritten function then becomes:
function join_bitmap(hex_lower_word, hex_upper_word)
{
var lower_word = parseInt(hex_lower_word, 16);
var upper_word = parseInt(hex_upper_word, 16);
var mask15 = 0x7fff;
var bit15 = 0x8000;
var bit31 = 0x80000000;
return 0xffffffff & (((upper_word&mask15)<<16) | lower_word) + ((upper_word & bit15)?bit31:0);
}
There isn't just a single "hard coded special case" - there are 2 billion or so. This takes care of all of them.

JavaScript - Find out how many times a number goes into another number evenly

Is there a simple way to find how many times a number goes into another number evenly in JavaScript?
Say 11 divided by 4 --- I know 4 goes into 11 2 times evenly
I have this code but I thought there was a simpler way that I maybe forgetting?
<script>
a = 11;
b = 4;
i = a % b;
i2 = a - i;
solution = i2 / b;
document.write(solution); // 2
</script>
What about...
Math.floor(11 / 4);
If you're wanting to handle negative numbers (thanks Ted Hopp), you could use ~~, |0 or any other bitwise trick that will treat its operand as a 32 bit signed integer. Keep in mind, besides this being confusing, it won't handle a number over 32bits.
~~(11 / 4);
You can use this trick:
(a / b) >> 0
Shifting by 0 truncates the fractional part. This will always round toward 0, which Math.floor will not do with negative numbers.

numbers and toFixed , toPrecision in Javascript?

Regarding the famous issue of 1.01+1.02 which is 2.0300000000000002
one of the workarounds is to use toFixed : e.g.
(1.01+1.02).toFixed(2) --->"2.03"
But I saw a solution with toPrecision
parseFloat((1.01+1.02).toPrecision(10))-->"2.03"
But lets have a look at n in
toFixed(n)
toPrecision(n)
How would I know what is n ?
0.xxxxxxxxxxx
+
0.yyyyyyyyyyyyy
---------------------
0.zzzzzzzzzzzzzzzzzzzzzzzzz
^
|
-----??????------
each number being added can have a different decimal digits...
for example :
1.0002+1.01+1.03333--> 3.0435300000000005
how would I calculate the n here ? what is the best practice for this (specific) issue ?
For addition as in this situation I would check the number of decimal places in each operand.
In the simplest of situations the number of decimal places in the operand with the greatest number of decimal places is the value of n.
Once you have this, use which ever method you like to truncate your value. Then get rid of trailing zeros.
You may encounter trailing zeros in situations such as 1.06 + 1.04, the first step would take you to 1.10 then truncating the zero would give 1.1
In your last example 1.0002+1.01+1.03333 greatest number of decimal places is 5 so you are left with 3.04353 and there are no trailing zeros to truncate.
This returns the expected output:
function add(){
// Initialize output and "length" properties
var length = 0;
var output = 0;
// Loop through all arguments supplied to this function (So: 1,4,6 in case of add(1,4,6);)
for(var i = 0; i < arguments.length; i++){
// If the current argument's length as string is longer than the previous one (or greater than 0 in case of the first argument))
if(arguments[0].toString().length > length){
// Set the current length to the argument's length (+1 is to account for the decimal point taking 1 character.)
length = arguments[0].toString().length +1;
}
// Add the current character to the output with a precision specified by the longest argument.
output = parseFloat((output+arguments[i]).toPrecision(length));
}
// Do whatever you with with the result, here. Usually, you'd 'return output;'
console.log(output);
}
add(); // Returns 0
add(1,2,3); // Returns 6
add(1.01,2.01,3.03); // Returns 6.05
add(1.01,2.0213,3.3333); // Returns 6.3646
add(11.01,2.0213,31.3333); // Returns 44.3646
parseFloat even gets rid of trailing zero's for you.
This function accepts as many numbers as parameters as you wish, then adds these together taking the numbers' string length into account, when adding them. The precision used in the addition is dynamically modified to fit the "currently added" argument's length.
Fiddle
If you're doing calculations, you have a couple of choices:
multiply the numbers by eg 100, to convert to integers, then do the calculations, then convert back again
do the calculations, dont worry about the rounding errors, then round the result at display time
If you're dealing with money/currencies, the first option is probably not a bad option. If you're just doing scientific maths, I would personally not worry about it, and just round the results at display time, eg to 6 significant figures which is the default for my c++ compiler (gcc; not sure if it is in the c++ standards or not, but if you print 1.234567890 in gcc c++, the output is 1.23457, and the problem is avoided)
var a = 216.57421;
a.toPrecision(1); // => '200' because 216 with 1 < 5;
a.toPrecision(2); // => '220' because 216 with 6 >= 5;
a.toFixed(1); // => 216.6 because 7 >= 5;
a.toFixed(2); // => 216.57 because 4 < 5;

Categories