简体   繁体   中英

integer number of alternative length (not 32-bit) in javascript

The problem is as follows: I need to deal with numbers that are encoded exactly as signed integer (the MSB is sign, the value is 2's complement binary value), but they are not 32 bit. Ie I have a 21bit binary value, which I have to treat so that 20th bit is sign and bits 19-0 represent the number code. And I need to do something like

int<21>a = 200000
int<21>b = 300000
int<21>c = a + b

the target language is javascript, ie all the standard binary operations like bit-wise add/shift are available. Is there a simple algorythm?

Natively it is not possible to have 21 bit Integers. But as you need Integeres less than 2^20 they are anyway small enough to fit into the bits 0 to 19.
Without more information my advice would be, to add 2^20 = 1048576 to every integer as the sign. Then you have to be careful when doing operations with them, so implement the basic math operations on your own with respect to 2^20 as the sign.

Some time has passed, but I'll just leave here a resulting javascript code, just in case someone else needs it, this function converts 32 bit int value to N-bit int:

function 32BitsToN (intValue) {
  var retVal=0;
  var leftMask = 0;

  var flag = (1 << N-1);
    if ((value & flag )!= 0) { //Nth bit is set, the value is negative.
      //WScript.Echo('NEGATIVE!\n');
      //WScript.Echo('Incoming: '+value)
      //we need to set all bits N-32 to 1
  for (var i = 1; i<= (32-N); i++) {
    leftMask |= 1<<32-i;
  }

    retval = value | leftMask;      
    //incoming: |1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|x|x|x|x|x|
    //Mask:     |1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|1|0|0|0|0|0|0|
    //result:   |0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|1|x|x|x|x|x|

  } else {
    retval = value;
  }

return retval;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM