Signed to Unsigned and Vice Versa (arithmetical)

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 have a number that goes e.g. from 0 to 65535 and I want to convert it to a reasonable signed value.

e.g.: 65535 should become -1.

Please do not use any bit related operations but something arithmetical.

I guess this should be language independent assuming that we use a data type that is big enough.

Update: Implementation according to the answer further down:

function convertWordToShort(ival) {
    if (isNaN(ival) === false) {
        if (ival > 32767) {
            ival = ival - 65536;
        }
    }
    return ival;
}
function convertShortToWord(ival) {
    if (isNaN(ival) === false) {
        if (ival < 0) {
            ival = ival + 65536;
        }
    }
    return ival;
}
function convertIntToDWord(ival) {
    if (isNaN(ival) === false) {
        if (ival < 0) {
            ival = ival + 4294967296;
        }
    }
    return ival;
}
function convertDWordToInt(ival) {
    if (isNaN(ival) === false) {
        if (ival > 2147483647) {
            ival = ival - 4294967296;
        }
    }
    return ival;
}

Answers:

Answer

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

if(x > 32767) {x = x - 65536;}
Answer

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

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

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.