Signed to Unsigned and Vice Versa (arithmetical)

后端 未结 3 841
逝去的感伤
逝去的感伤 2021-01-16 13:43

How to convert a number from unsigned to signed?

signed: -32768 to 32767 unsigned: 0 to 65535

I am solving the problem in JavaScript. The situation is that I

相关标签:
3条回答
  • 2021-01-16 13:51

    function signed(bits, value) { return value & (1 << (bits - 1)) ? value - (1 << bits) : value; }

    signed(8, 0xFF); // returns -1

    signed(16, 0xFF); // returns 255

    0 讨论(0)
  • 2021-01-16 14:16

    In the case that you would be looking for bitwise operation related answers, you could try the following:

    • to convert something akin to a 16 bit unsigned integer (i.e 0 <= n <= 65535) to a 16 bit signed one:
    (number << 16) >> 16
    
    • Or:
    new Int16Array([number])[0]
    

    Where number in both cases is your 16 bit number.

    As a side note the reason the first solution works is because if you bit shift to the right 16 times, the most significant bit of your 16 bit number will actually become the most significant bit of the 32 bit JavaScript integer (so if the most significant bit was a 1, it'd make the number negative), and so when you shift it to the left 16 times it'd shift while keeping the standard 2s complement form and retain the value/sign it gained from being shifted to the right previously, see this Wikipedia article for more:
    https://en.m.wikipedia.org/wiki/Arithmetic_shift

    0 讨论(0)
  • 2021-01-16 14:17

    Just test if the number is over halfway, then subtract the modulus.

    if(x > 32767) {x = x - 65536;}
    
    0 讨论(0)
提交回复
热议问题