Change base in javascript - javascript

I have a number and this number's base is 32. I need to convert base to 10. How can I do this with javascript ?
var testip="17b3uvp";
var donus=testip.toString(10);
alert(donus)
It is not working.

You use parseInt telling it to use base 32, and then toString:
var testip = "17b3uvp";
var parsed = parseInt(testip, 32);
var donus = parsed.toString(); // 10 is the default, but you can specify it for emphasis/clarity if desired
alert(donus);
The reason your code wasn't working is that you never converted the string to a number. Calling toString on a string just gives you back that string (and String's toString doesn't take any arguments). So first we get a number, parsing the string in the right number base, and then we use Number's toString to create a string in decimal (Number's toString does accept a number base, but 10 is the default).

For base conversion in Javascript using parseInt, use the below format
parseInt(string,base)
base can be any number between 2 and 32.
In your case
var testip="17b3uvp";
var donus=parseInt(testip,10);
alert(donus)
This will alert 17 as result.

Related

why parseInt() in javascript converting "1abc" to 1?

I am trying to understand how parseInt() will work in javascript, my scenarios are
var x = parseInt("123");
console.log(x); // outputs 123
var x = parseInt("1abc");
console.log(x); // outputs 1
var x = parseInt("abc");
console.log(x); // outputs NaN
as of my observation parseInt() converts a string to integer(not really an integer of string like "12sv") when the string begins with number.
but in reality it should return NaN.
From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
"If the first character cannot be converted to a number, parseInt returns NaN."
From Mozilla's docs: "If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point."
So it will parse up to the first invalid character, drop the rest of the string, and return the int it managed to parse until then. If there's no valid characters it will return NaN.
parseInt()->it simply parse the provided value to its equivalent radix conversion,if specified without radix it converts to decimal equivalent.
for coercion purpose, we should avoid using parseInt,we can use Number() function instead.

Why does hex value is returned as a number in javascript

I tried the following code in a browser console.
var testingVar = 0xffff00;
When I access the variable it returned me the value 16776960 instead of the hexa value. Why does this happen? can't we store hexa value in the variable.
There's no such thing as a "hex value" in Javascript. There are strings and numbers.
0xffff00 is just an alternate syntax for specifying a number. By default the console will print numbers in decimal (base 10), which is why you see 16776960.
You can see a string representation of the number, using a different base with the toString method.
// hex
(0xffff00).toString(16) // "0xffff00"
// decimal
(0xffff00).toString(10) // "16776960"
// octal (for good measure)
(0xffff00).toString(10) // "77777400"
You can use hexadecimals in Javascript.
When you need to convert an octal or hexadecimal string to a number, use the function parseInt(str,base). Consider these examples, first you should define like below
var testingVar = '0xffff00';
And when you need you can call like below:
num = parseInt(testingVar, 16);

Javascript String to int conversion

I have the following JS immbedded in a page:
var round = Math.round;
var id = $(this).attr("id");
var len = id.length;
var indexPos = len -1; // index of the number so that we can split this up and used it as a title
var pasType = id.substring(0, indexPos); // adult, child or infant
var ind = round(id.substring(indexPos)); // converts the string index to an integer
var number = (id.substring(indexPos) + 1); // creates the number that will go in the title
window.alert(number);
id will be something like adult0, and I need to take that string and split it into adult and 0 - this part works fine.
The problem comes in when I try to increment the 0. As you can see I use Math.round to convert it to an integer, and then add 1 to it - I expect 0 to be 1 after this. However, it doesn't seem to be converting it to integer, because I get 01, not 1. When testing this with adult1 the alert I get is 11.
I'm using this question for reference, and have also tried var number += id.substring(indexPos);, which breaks the JS (unexpected identifier '+=')
Does anyone know what I'm doing wrong? Is there a better way of doing this?
The parseInt() function parses a string and returns an integer,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
This is to do with JavaScript's + in operator - if a number and a string are "added" up, the number is converted into a string:
0 + 1; //1
'0' + 1; // '01'
To solve this, use the + unary operator, or use parseInt():
+'0' + 1; // 1
parseInt('0', 10) + 1; // 1
The unary + operator converts it into a number (however if it's a decimal it will retain the decimal places), and parseInt() is self-explanatory (converts into number, ignoring decimal places).
The second argument is necessary for parseInt() to use the correct base when leading 0s are placed:
parseInt('010'); // 8 in older browsers, 10 in newer browsers
parseInt('010', 10); // always 10 no matter what
There's also parseFloat() if you need to convert decimals in strings to their numeric value - + can do that too but it behaves slightly differently: that's another story though.
Convert by Number Class:-
Eg:
var n = Number("103");
console.log(n+1)
Output: 104
Note:- Number is class. When we pass string, then constructor of Number class will convert it.
JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:
var numberAsInt = parseInt(number, 10);
// Second arg is radix, 10 is decimal.
If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.
Although parseInt is the official function to do this, you can achieve the same with this code:
number*1
The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.
Use parseInt():
var number = (parseInt(id.substring(indexPos)) + 1);` // creates the number that will go in the title
If you are sure id.substring(indexPos) is a number, you can do it like so:
var number = Number(id.substring(indexPos)) + 1;
Otherwise I suggest checking if the Number function evaluates correctly.

JavaScript treats numbers as strings, not integers, and ParseInt doesn't fix it

I'm trying to insert two numbers in two input type text fields. After I do that, I have to make sure than the first number is smaller than the second. To do this, I'm capturing both fields like this:
var supt = $('#suptotal').val();
var supc = $('#supcubierta').val();
When I compare the two variables, they are strings, so for example 21 is considered bigger than 123.
I've tried to use the function ParseInt, like this
var supt = ParseInt($('#suptotal').val());
but it didn't work. How can I compare the numbers as numbers?
use parseInt($('#suptotal').val(), 10) as against ParseInt($('#suptotal').val(), 10)
The function names are case sensitive
parseInt( $('#suptotal').val(), 10 );
Specify a radix as well, incase the string contains something like '010' which would be interpreted as an octal and result in 8.
ParseInt($('#suptotal').val());
You've written the function incorrectly. parseInt is defined in a lowerCamelCase style.
parseInt($('#suptotal').val());
It is also advised that you specify the radix parameter with 10 for base 10.
parseInt($('#suptotal').val(), 10);
But if you are simply wanting to convert the string into a number, use the unary effect of the binary operator +, which will coerce a value into a number when used on a single operand:
var supt = +$('#suptotal').val();

How to convert binary representation of number from string to integer number in JavaScript?

Can anybody give me a little advice please?
I have a string, for example "01001011" and what I need to do is to reverse it, so I used .split('') than .reverse() and now I need to read the array as a string and convert it to integer. Is it possible?
Thanks
If you want to convert the array back to a string use join() (MDN) and for converting a string to an integer use parseInt() (MDN). The second argument of the later is an optional radix.
JavaScript will try to determine, what radix to use, but to be sure you should always add your radix manually. Citing from MDN:
If radix is undefined or 0, JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
So in your case the following code should work:
var a = '01001011';
var b = parseInt( a.split('').reverse().join(''), 2 );
or just (if you would want to convert the starting string, without the reversal):
var b = parseInt( a, 2 );
Just call parseInt with a different radix, in this case use 2 for binary.
var a = parseInt("01001011", 2);
// a === 75
parseInt attempts to figure out the radix itself when you don't explicitly specify it. From the Mozilla Developer Network:
If radix is undefined or 0, JavaScript assumes the following:
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
If the input string begins with any other value, the radix is 10 (decimal).
In this case, it is crucial that you do specify the radix, as otherwise it may be interpreted as either a decimal or an octal number. As a rule of thumb, always specify the radix.
This will take a buffer hex and convert it to a binary str and back to the buffer hex.
NOTE: when I say a buffer hex, I mean a decimal value because when you iterate over a buffer and pull each item in the array, it gives you the decimal value (eg: 210, instead of d2).
var buffer - new Buffer([0, 210, 242]); // Node
// var arrayBuffer = new ArrayBuffer(3); // JavaScript
// var uint8 = new Uint8Array(arrayBuffer); // JavaScript/ 16Array, 32Array, etc
Need to be acquainted with buffers
You'll iterate over the buffer with a for(){} and inside you can do something like:
(210).toString(2); // '11010010'
(210).toString(16); // 'd2' (untested)
(210).toString(8); // (Octal-Digits representation)
parseInt((210).toString(2), 2); // 210
parseInt((210).toString(2), 2).toString(16); // 'd2'
Obviously, instead of using "(210).toString(2)" IN YOU FOR LOOP, you would use "(buffer[i]).toString(2)"
Endian Rep is up to you! :) (array.reverse())
Hope this helps!
PS. parseInt(('00000' + (210).toString(2).substring(5, 8)), 2); // 2
parseInt((210).toString(2).substring(5, 8), 2); // 2

Categories