签署无签名和副Versa(算术) [英] Signed to Unsigned and Vice Versa (arithmetical)

查看:61
本文介绍了签署无签名和副Versa(算术)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数字从无符号转换为有符号?

How to convert a number from unsigned to signed?

已签名:-32768至32767
无符号:0至65535

signed: -32768 to 32767 unsigned: 0 to 65535

我正在解决JavaScript中的问题。情况是,我有一个例如从0到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.

例如:65535应该变为-1。

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;
}


推荐答案

只测试数字是否为超过一半,然后减去模数。

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

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

这篇关于签署无签名和副Versa(算术)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆