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 ?
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 ?
Share Improve this question edited May 4, 2018 at 17:20 Serge Seredenko 3,5417 gold badges23 silver badges40 bronze badges asked May 4, 2018 at 16:14 Mehdi SouregiMehdi Souregi 3,2655 gold badges38 silver badges58 bronze badges 3 |4 Answers
Reset to default 9You 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.
&
on a string and an integer. – Patrick Roberts Commented May 4, 2018 at 16:16