PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to convert a binary number into a Signed decimal number

 August 07, 2022     binary, decimal, javascript     No comments   

Issue

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


Solution

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


Answered By - Paul S.
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing