最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to convert an integer to short in javascript - Stack Overflow

programmeradmin1浏览0评论

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
  • 1 In JavaScript, there is no such thing as "casting". Also I'm not sure what you expected to happen when using binary and & on a string and an integer. – Patrick Roberts Commented May 4, 2018 at 16:16
  • Yes there's no specific types in javascript, i mean not available for you to define, that's the compiler job, hence the 'var' keyword, don't confuse it with the C# var keyword. – user7148391 Commented May 4, 2018 at 16:18
  • the desired output is -24 , i know there is no such type on javascript – Mehdi Souregi Commented May 4, 2018 at 16:19
Add a comment  | 

4 Answers 4

Reset to default 9

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.

发布评论

评论列表(0)

  1. 暂无评论