Chait
Chait

Reputation: 501

How to convert a binary number into a Signed decimal number

I have a binary number something like this.. var data = "1100110010". I am trying to convert this into appropriate signed decimal number in Javascript.

The steps I use are following

1) var data = "1100110010"; var bin2dec = parseInt(data,2).toString(10);

The bin2dec gives the converted Decimal number as "818" .

But I want to access the signed decimal of the binary number too.

The signed decimal number for this binary code is "-206".

How can I access both signed and unsigned decimal Value from a given Binary Number. Please let me know . Any ideas would help

Upvotes: 2

Views: 6245

Answers (5)

mplungjan
mplungjan

Reputation: 177786

This will take an unknown bit pattern <= 32 bits and if it is < 8 bits convert to positive int and if >= 8 with a leading 1, a negative signed int.

The trick is to pad to 32 before parseInt

const getSigned = binStr => parseInt(binStr.length >= 8 && binStr[0] === "1" ?
  binStr.padStart(32, "1") : binStr.padStart(32, "0"), 2) >> 0;

const signed = [
  "1100110010",   // -206
  "11111011",     //   -5
  "01111011",     //  123
  "1111111111000" //   -8
].map(getSigned);

console.log(signed);

Upvotes: 0

Eladian
Eladian

Reputation: 958

Some other ways:

const bin = "1100110010"
const decimal = parseInt(bin,2)
const numBits = bin.length

let p = 0x80000000 >> (32 - numBits) 

console.log(p | decimal)
//or:
console.log(parseInt(bin.padStart(32,'1'),2) | 0)

Upvotes: 1

James Wright
James Wright

Reputation: 3010

It's possible to convert binary numbers to signed decimals using JavaScript's typed arrays.

const unsigned = 0b1111111100110010;
const [ signed ] = new Int16Array([0b1111111100110010]);

console.log(unsigned); // => 65330
console.log(signed); // => -206

I'm sure this will be less performant than bitwise operations, but it's certainly less code.

Upvotes: 5

Gerd K
Gerd K

Reputation: 1147

Is that what you want?

var data = "1100110010";
var bin2dec = parseInt(data,2).toString(10);
var signed = (data.substr(0,1) === '1' ? '-':'+') + parseInt(data.substr(1),2);

This will give you -306 for the signed number. I am not sure if you had a typo in the number you indicated in your question (-206).

Probably not the best solution, but should work. You might still want to check the number of binary digits before deciding if it is signed.

Upvotes: 1

Paul S.
Paul S.

Reputation: 66324

Using some bit-shifting trickery

function uintToInt(uint, nbit) {
    nbit = +nbit || 32;
    if (nbit > 32) throw new RangeError('uintToInt only supports ints up to 32 bits');
    uint <<= 32 - nbit;
    uint >>= 32 - nbit;
    return uint;
}

uintToInt(818, 10); // -206
  • Why 818? Because this is the uint value of your binary string

    parseInt('1100110010', 2); // 818
    
  • Why 10? Because your signed int is represented by 10 bits in your binary string

    '1100110010'.length; // 10
    

Please note that for positive numbers, you can't just take nbit = str.length; as the string may not be 0-padded, you'll need to know how many bits you're actually using

You may also want to throw an error for uint > 4294967295


For completeness,

function intToUint(int, nbit) {
    var u = new Uint32Array(1);
    nbit = +nbit || 32;
    if (nbit > 32) throw new RangeError('intToUint only supports ints up to 32 bits');
    u[0] = int;
    if (nbit < 32) { // don't accidentally sign again
        int = Math.pow(2, nbit) - 1;
        return u[0] & int;
    } else {
        return u[0];
    }
}

intToUint(-206, 10); // 818

Upvotes: 2

Related Questions