How to convert an integer to short in javascript - javascript

I have on my server side (c#) an integer a:
int a = 65512;
and when I can cast it to short : (short)a is equal to -24
I want to move on this conversion to the client side (javascript)
I tried to convert it to first to binary : a.toString(2) and then do an a.toString(2) & 0xFF but in vain
How can I cast a number to a short one on javascript side ?

You can coerce a number in JavaScript to a particular numeric type by making use of TypedArray's, specifically, Int16Array:
function toShort(number) {
const int16 = new Int16Array(1)
int16[0] = number
return int16[0]
}
console.log(toShort(65512))

JavaScript doesn't have int and short and such, it has number, which is an IEEE-754 double-precision binary floating point type (and typed arrays as in Patrick Roberts' answer). However, for certain operations, it acts like it has a 32-bit integer type.
You could take your number and use bit shifting operators to lose half of that 32-bit value, like this:
var a = 65512;
a = (a << 16) >> 16;
console.log(a);

Another option is to understand that C# is overflowing the number so you can just check it's over the max value for a short which is 32767 (07FFF) and subtract the max value of an int+1 which is 65536 (0x10000). For example:
var number = 65512
var shortValue = number > 0x7FFF ? number - 0x10000 : number;
console.log(shortValue);

JavaScript does not support variable types such as short.
You'll have to handle ensuring the number is in short on the server side and keep it as a string in the JavaScript side.

Related

How can i get the same number value as given in JavaScript?

I got a number 1267508826984464384 from json response. Here i print the number.
<script>
var num = 1267508826984464384;
console.log(num);
var num = "1267508826984464384";
console.log(num);
</script>
output is
In the first print the output is different from the original value. I need the same value as given.
Is it possible?
JavaScript uses floating point under the hood to store numbers. Floating point double precision, which is what JavaScript uses, can only store 64 bits of data. With the way numbers are represented in this manner, this means that there's a limit to how big a Number can normally be (2^53 - 1 for double precision floating point). Your number in the example has gone over this limit (overflow) and hence is being rounded by JavaScript.
You can use BigInt:
var num = BigInt(1267508826984464384);
console.log(num); // logs 1267508826984464384n, with n representing that it's a BigInt type
var num = "1267508826984464384";
console.log(num); // logs 1267508826984464384
May be helpful to read What Every Programmer Should Know About Floating-Point Arithmetic for more information on why this is the case.
They are different types (int and string, respectfully). What you are seeing in the top example is integer overflow (safely abstracted by JS). You can use a big integer to bypass this issue
const hugeString = BigInt("1267508826984464384")
console.log(hugeString + 1n) // 1267508826984464385n
The type of this is BitInt and it will safely allow you to represent your number as a integer. This type must be treated different and the additions must also be BigInt (as shown in the example above).
BigInt is a built-in object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number primitive and represented by the Number.MAX_SAFE_INTEGER constant. BigInt can be used for arbitrarily large integers.
From MDN. You can use it like so:
const theBiggestInt = 9007199254740991n
const alsoHuge = BigInt(9007199254740991)
// ↪ 9007199254740991n
const hugeString = BigInt("9007199254740991")
// ↪ 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff")
// ↪ 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111")
// ↪ 9007199254740991n
RegEx for finding numbers and quoting them. Looks for prop value boundaries and a sequence of digits and optionally one period, and replaces inserting with quotes around the number value.
RegEx should be adjusted for maximum length or tolerances for numbers to be quoted as strings.
key or value prefix/suffix can be added, so that a JSON.parse reviver function can recognize them and parse to big.js or BigInt.
In most cases, you probably already know if you might receive a large number, and could probably just use a trivial RegEx replace on the specific property you need.
And, you should be coordinating with the server-side to give the data to you in another form that is safe to consume.
Parsing number strings using BigInt and big.js.
str = String.raw `{"j\"son":1234561251261262131231231231231231231231231232123123123,
"array":
[123123123124124214124124124124.111,
124124124124124124124124124,
124124124124124124124124
]}
`
str = str.replace(/((?:{|,|\[)\s*(?:"(?:[^"]|\\")+"\s*:\s*)?)(\d+\.?\d*)(\s*)(?=,|}|\])/g, `$1"$2"$3`)
// note: capture group $3 is just whitespace, which can normally be ignored; included to be "technically accurate"
console.log(
str,
(BigInt(JSON.parse(str)[`j"son`]) + 1n).toString(),
(Big(JSON.parse(str).array[0]).plus(0.0003)).toFixed()
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/big.js/5.2.2/big.min.js" integrity="sha256-gPNmhPlEOUlyAZomtrYRW/HSIjBOOl2LVxft3rsJpxI=" crossorigin="anonymous"></script>

why does javascript bitwise & on binary numbers increases length of binary string

In the following code it is my understanding that & is supposed to give a resulting binary string with ones where each corresponding digit on each string are both 1's, however the result I got is: "98435", what I expected was: "101011". Where is my misunderstanding? how can I achieve what I am attempting to do?
const bool = "101011";
const bool2 = "111011";
const and = bool & bool2;
console.log("bool: "+bool+", bool2: "+bool2+", &: "+and);
Javascript, like most languages, assumes humans use base 10 in code
Your code uses STRINGS though
When you use any mathematical operator (except +) Javascript tries to be nice, and make a Number out of the string - but, it's a BASE 10 number (unless the first digit in the string is a 0 and the rest of the digits are octal (0 to 7), in that case, the number is considered to be an BASE 8)
So the string 101011 is "coerced" to be the Number 101011 = 11000101010010011 and 111011 becomes 111011 = 11011000110100011
11000101010010011 (binary) &
11011000110100011 (binary)
-----------------
11000000010000011 (binary) = 98435 (decimal)
However, easy to fix:
const bool = "101011";
const bool2 = "111011";
const and = (parseInt(bool,2) & parseInt(bool2,2)).toString(2);
console.log("bool: "+bool+", bool2: "+bool2+", &: "+and);

Translation into another number system JS

I have a string and I need to convert this string into another number system.
1959113774617397110401052 - in Decimal notation to thirty-tensary number system (10 to 36).
If i try to use this code:
var master = 1959113774617397110401052;
parseInt(master, 10).toString(36);
//8v0wc05bcz000000
It doesn't work properly.
Can you help me to know, where is my mistake and how to use this correctly.
Thank you!
The maximum integer JavaScript can safely handle is 9007199254740991. This is what we get if we call Number.MAX_SAFE_INTEGER. Your number, on the other hand, is significantly larger than this:
9007199254740991
1959113774617397110401052
Because of this, JavaScript isn't able to safely perform mathematical calculations with this number and there's no guarantee that you'll get an accurate result.
The MAX_SAFE_INTEGER constant has a value of 9007199254740991. The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(253 - 1) and 253 - 1.
Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information.
— MDN's notes on Number.MAX_SAFE_INTEGER
You would need to use a multi-precision library like Decimal.js for integer calculations that exceed the range of signed Int32 resp. the continuous integer range representable by 64bit floats. As example:
var astr = '1959113774617397110401052'
var a =new Decimal(astr)
var out = '';
while( a > 0 ) {
var d = a.mod(36).toNumber();
a = a.divToInt(36);
if(d>9) d=d+39; // d+7 for upper case
out = String.fromCharCode(48+d)+out
}
var my_div = document.getElementById("my_div")
my_div.innerHTML += astr+" in base 36 is "+out;
<script src="https://raw.githubusercontent.com/MikeMcl/decimal.js/master/decimal.min.js"></script>
<div id="my_div"></div>

Javascript : How to increase a fraction value in a textbox ? example: 0.10 to 0.11 [duplicate]

This question already has answers here:
How to add two strings as if they were numbers? [duplicate]
(20 answers)
how to sum two numbers from input tag? [duplicate]
(2 answers)
Closed 9 years ago.
I need to increase a fraction in a text box
using javascript.
the goal is to add 1 penny until it is 0.99
and then it will be 1.00 and 1.01
how can this be done in javascript?
this is what is not working.
var a;
a = document.getElementById('a1').value;
a = a+a;
alert(a);
alert returns
0.100.10
Additional Info
var a;
a = parseFloat(document.getElementById('b13').value);
a = a+a;
alert(a);
returns
0.2
i would rather see 0.20
but most importantly, how do increase this by 0.01 at a time ?
SOLVED:
both
var a;
a = parseFloat(document.getElementById('a1').value);
a = a+0.01;
alert(a);
}
and ...
document.getElementById('a1').value = +document.getElementById('a1').value + 0.01
worked fine.
Text box returns the value as string so parse it
var a;
a = parseFloat(document.getElementById('a1').value);
a = (a+a).toFixed(2);
alert(a);
And it doesn't adds 0.01 to a .. It doubles the a so use something like this.
var a;
a = parseFloat(document.getElementById('a1').value);
a = (a + 0.01).toFixed(2);
alert(a);
a = a+a doesn't add .01. It would double a if a was a number, but since javascript is seeing it as a string, it just concatenates it.
You want a = +a+0.01.
This will add 0.01 to the value of a. The initial + is to make sure that javascript treats a as a number instead of a string.
This will work fine for your alert, but then you still need to set the value back:
document.getElementById('a1').value = a
Or, to put it all in one line (using the toFixed addition from HMR):
document.getElementById('a1').value = (+document.getElementById('a1').value + 0.01).toFixed(2)
First convert a into float like this,
a = parseFloat(document.getElementById('a1').value);
Then add and convert a to float like this,
a = (a + a).toFixed(2)
and alert the answer.
a is containing a string, instead of a number. string + string returns the concatenation of the two strings - you haven't told Javascript it's a number, so it doesn't treat it like one.
You can use parseFloat and parseInt to turn strings into floating point numbers (have decimal places) or integers (do not). http://www.javascripter.net/faq/convert2.htm
However, be aware that floating point numbers have inaccuracies due to being stored in limited amount of memory - they will round off after a certain number of places (and not decimal places - binary places, for example 0.1 cannot be represented exactly as a floating point number, despite being only one decimal place in base 10!), and if you need to do important financial calculations, you should be aware of this inaccuracy (for example, you might use a fixed point number system instead). Read What Every Computer Scientist Should Know About Floating-Point Arithmetic for more information.

Fastest way to create this number?

I'm writing a function to extend a number with sign to a wider bit length. This is a very frequently used action in the PowerPC instruction set. This is what I have so far:
function exts(value, from, to) {
return (value | something_goes_here);
}
value is the integer input, from is the number of bits that the value is using, and to is the target bit length.
What is the most efficient way to create a number that has to - from bits set to 1, followed by from bits set to 0?
Ignoring the fact that JavaScript has no 0b number syntax, for example, if I called
exts(0b1010101010, 10, 14)
I would want the function to OR the value with 0b11110000000000, returning a sign-extended result of 0b11111010101010.
A number containing p one bits followed by q zero bits can be generated via
((1<<p)-1)<<q
thus in your case
((1<<(to-from))-1)<<from
or much shorter
(1<<to)-(1<<from)
if you have the number 2^q (= 1 shifted left by q) represented as an integer of width p + q bits, it has the representation:
0...010...0
p-1 q
then 2^q - 1 has the representation
0...01...1
p q
which is exactly the opposite of you want. So just flip the bits
hence what you want is NOT((1 LEFT SHIFT by q) - 1)
= ~((1 << q) - 1) in c notation
I am not overly familiar with binary mathematics in JavaScript... But if you need to OR a number with 0b11110000000000, then I assume you would just convert that to decimal (which would get you 15360), and do value | 15360.
Relevant info that you may find useful: parseInt("11110000000000", 2) converts a binary number (specified as a string) to a decimal number, and (15360).toString(2) converts a decimal number (15360 in this case) to a binary number (the result is a string).
Revised solution
There's probably a more elegant and mathematical method, but here's a quick-and-dirty solution:
var S = "";
for(var i=0;i<p;i++)
S += "1";
for(i=0;i<q;i++)
S += "0";
S = parseInt(S, 2); // convert to decimal

Categories