JavaScript:将(十六进制)有符号整数转换为javascript值 [英] Javascript: convert a (hex) signed integer to a javascript value

查看:341
本文介绍了JavaScript:将(十六进制)有符号整数转换为javascript值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用十六进制数字表示的带符号值,例如0xffeb,并希望将其转换为-21作为常规" Javascript整数.

I have a signed value given as a hex number, by example 0xffeb and want convert it into -21 as a "normal" Javascript integer.

到目前为止,我已经写了一些代码:

I have written some code so far:

function toBinary(a) { //: String
    var r = '';
    var binCounter = 0;
    while (a > 0) {
        r = a%2 + r;
        a = Math.floor(a/2);
    }
    return r;
}

function twoscompl(a) { //: int
    var l = toBinaryFill(a).length;
    var msb = a >>> (l-1);

    if (msb == 0) {
        return a;
    }

    a = a-1;
    var str = toBinary(a);
    var nstr = '';
    for (var i = 0; i < str.length; i++) {
        nstr += str.charAt(i) == '1' ? '0' : '1';
    }
    return (-1)*parseInt(nstr);
}

问题是,我的函数对于两个数字都返回1作为MSB,因为只在二进制表示形式字符串"的MSB处查找.在这种情况下,两个数字均为1:

The problem is, that my function returns 1 as MSB for both numbers because only at the MSB of the binary representation "string" is looked. And for this case both numbers are 1:

-21 => 0xffeb => 1111 1111 1110 1011
 21 => 0x15   =>              1 0101

您是否有任何想法来实现这种更高效,更好的服务?

Have you any idea to implement this more efficient and nicer?

问候, 神话

推荐答案

使用parseInt()进行转换(仅接受您的十六进制字符串):

Use parseInt() to convert (which just accepts your hex string):

parseInt(a);

然后使用掩码找出是否设置了MSB:

Then use a mask to figure out if the MSB is set:

a & 0x8000

如果该函数返回非零值,则表示它为负数.

If that returns a nonzero value, you know it is negative.

将其全部包装起来:

a = "0xffeb";
a = parseInt(a, 16);
if ((a & 0x8000) > 0) {
   a = a - 0x10000;
}

请注意,这仅适用于16位整数(C中的short).如果您使用的是32位整数,则需要使用其他掩码和减法.

Note that this only works for 16-bit integers (short in C). If you have a 32-bit integer, you'll need a different mask and subtraction.

这篇关于JavaScript:将(十六进制)有符号整数转换为javascript值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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