Javascript: convert a (hex) signed integer to a javascript value












7














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


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?



Greetings,
mythbu










share|improve this question



























    7














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


    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?



    Greetings,
    mythbu










    share|improve this question

























      7












      7








      7


      2





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


      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?



      Greetings,
      mythbu










      share|improve this question













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


      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?



      Greetings,
      mythbu







      javascript sign






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '12 at 7:32









      mythbu

      189315




      189315
























          4 Answers
          4






          active

          oldest

          votes


















          11














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



          parseInt(a);


          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.



          To wrap it all up:



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


          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.






          share|improve this answer



















          • 2




            you should minus 0x10000
            – xiaoyi
            Nov 20 '12 at 7:44










          • @xiaoyi you're right, fixed it.
            – Bart Friederichs
            Nov 20 '12 at 7:45










          • Not sure how important it is, but since you're working with hex with parseInt, you probably want to use parseInt(a, 16)
            – Ian
            Nov 20 '12 at 8:00










          • @Ian, I tested it in the Firebug console and parseInt("0xffeb") parses correctly. When omitting the 0x, it needs the radix. To be safe, it should be added always. I updated my answer.
            – Bart Friederichs
            Nov 20 '12 at 8:04












          • True that it works without, but parseInt works on normal int strings without it as well...unless you accidentally give bad input (like expecting radix 10 parsing but providing "012" for whatever reason) and getting 10. It seems to be a browser consistency thing too. I've just found it better to always supply the radix, even if you're working on the "normal" base 10. Just wanted to point it all out :)
            – Ian
            Nov 20 '12 at 8:07





















          9














          I came up with this



          function hexToInt(hex) {
          if (hex.length % 2 != 0) {
          hex = "0" + hex;
          }
          var num = parseInt(hex, 16);
          var maxVal = Math.pow(2, hex.length / 2 * 8);
          if (num > maxVal / 2 - 1) {
          num = num - maxVal
          }
          return num;
          }


          And usage:



          var res = hexToInt("FF"); // -1
          res = hexToInt("A"); // same as "0A", 10
          res = hexToInt("FFF"); // same as "0FFF", 4095
          res = hexToInt("FFFF"); // -1


          So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.






          share|improve this answer





























            0














            function hexToSignedInt(hex) {
            if (hex.length % 2 != 0) {
            hex = "0" + hex;
            }
            var num = parseInt(hex, 16);
            var maxVal = Math.pow(2, hex.length / 2 * 8);
            if (num > maxVal / 2 - 1) {
            num = num - maxVal
            }
            return num;
            }

            function hexToUnsignedInt(hex){
            return parseInt(hex,16);
            }


            the first for signed integer and
            the second for unsigned integer






            share|improve this answer





























              0














              Based on @Bart Friederichs I've come with:



              function HexToSignedInt(num, numSize) {
              var val = {
              mask: 0x8 * Math.pow(16, numSize-1), // 0x8000 if numSize = 4
              sub: -0x1 * Math.pow(16, numSize) //-0x10000 if numSize = 4
              }
              if(parseInt(num, 16) & val.mask > 0) { //negative
              return (val.sub + parseInt(num, 16))
              }else { //positive
              return (parseInt(num,16))
              }
              }


              so now you can specify the exact lenght.



              var numberToConvert = "CB8";
              HexToSignedInt(numberToConvert, 3);
              //expected output: -840





              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13468474%2fjavascript-convert-a-hex-signed-integer-to-a-javascript-value%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                11














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



                parseInt(a);


                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.



                To wrap it all up:



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


                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.






                share|improve this answer



















                • 2




                  you should minus 0x10000
                  – xiaoyi
                  Nov 20 '12 at 7:44










                • @xiaoyi you're right, fixed it.
                  – Bart Friederichs
                  Nov 20 '12 at 7:45










                • Not sure how important it is, but since you're working with hex with parseInt, you probably want to use parseInt(a, 16)
                  – Ian
                  Nov 20 '12 at 8:00










                • @Ian, I tested it in the Firebug console and parseInt("0xffeb") parses correctly. When omitting the 0x, it needs the radix. To be safe, it should be added always. I updated my answer.
                  – Bart Friederichs
                  Nov 20 '12 at 8:04












                • True that it works without, but parseInt works on normal int strings without it as well...unless you accidentally give bad input (like expecting radix 10 parsing but providing "012" for whatever reason) and getting 10. It seems to be a browser consistency thing too. I've just found it better to always supply the radix, even if you're working on the "normal" base 10. Just wanted to point it all out :)
                  – Ian
                  Nov 20 '12 at 8:07


















                11














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



                parseInt(a);


                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.



                To wrap it all up:



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


                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.






                share|improve this answer



















                • 2




                  you should minus 0x10000
                  – xiaoyi
                  Nov 20 '12 at 7:44










                • @xiaoyi you're right, fixed it.
                  – Bart Friederichs
                  Nov 20 '12 at 7:45










                • Not sure how important it is, but since you're working with hex with parseInt, you probably want to use parseInt(a, 16)
                  – Ian
                  Nov 20 '12 at 8:00










                • @Ian, I tested it in the Firebug console and parseInt("0xffeb") parses correctly. When omitting the 0x, it needs the radix. To be safe, it should be added always. I updated my answer.
                  – Bart Friederichs
                  Nov 20 '12 at 8:04












                • True that it works without, but parseInt works on normal int strings without it as well...unless you accidentally give bad input (like expecting radix 10 parsing but providing "012" for whatever reason) and getting 10. It seems to be a browser consistency thing too. I've just found it better to always supply the radix, even if you're working on the "normal" base 10. Just wanted to point it all out :)
                  – Ian
                  Nov 20 '12 at 8:07
















                11












                11








                11






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



                parseInt(a);


                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.



                To wrap it all up:



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


                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.






                share|improve this answer














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



                parseInt(a);


                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.



                To wrap it all up:



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


                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.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 20 '12 at 8:04

























                answered Nov 20 '12 at 7:42









                Bart Friederichs

                24.4k1162122




                24.4k1162122








                • 2




                  you should minus 0x10000
                  – xiaoyi
                  Nov 20 '12 at 7:44










                • @xiaoyi you're right, fixed it.
                  – Bart Friederichs
                  Nov 20 '12 at 7:45










                • Not sure how important it is, but since you're working with hex with parseInt, you probably want to use parseInt(a, 16)
                  – Ian
                  Nov 20 '12 at 8:00










                • @Ian, I tested it in the Firebug console and parseInt("0xffeb") parses correctly. When omitting the 0x, it needs the radix. To be safe, it should be added always. I updated my answer.
                  – Bart Friederichs
                  Nov 20 '12 at 8:04












                • True that it works without, but parseInt works on normal int strings without it as well...unless you accidentally give bad input (like expecting radix 10 parsing but providing "012" for whatever reason) and getting 10. It seems to be a browser consistency thing too. I've just found it better to always supply the radix, even if you're working on the "normal" base 10. Just wanted to point it all out :)
                  – Ian
                  Nov 20 '12 at 8:07
















                • 2




                  you should minus 0x10000
                  – xiaoyi
                  Nov 20 '12 at 7:44










                • @xiaoyi you're right, fixed it.
                  – Bart Friederichs
                  Nov 20 '12 at 7:45










                • Not sure how important it is, but since you're working with hex with parseInt, you probably want to use parseInt(a, 16)
                  – Ian
                  Nov 20 '12 at 8:00










                • @Ian, I tested it in the Firebug console and parseInt("0xffeb") parses correctly. When omitting the 0x, it needs the radix. To be safe, it should be added always. I updated my answer.
                  – Bart Friederichs
                  Nov 20 '12 at 8:04












                • True that it works without, but parseInt works on normal int strings without it as well...unless you accidentally give bad input (like expecting radix 10 parsing but providing "012" for whatever reason) and getting 10. It seems to be a browser consistency thing too. I've just found it better to always supply the radix, even if you're working on the "normal" base 10. Just wanted to point it all out :)
                  – Ian
                  Nov 20 '12 at 8:07










                2




                2




                you should minus 0x10000
                – xiaoyi
                Nov 20 '12 at 7:44




                you should minus 0x10000
                – xiaoyi
                Nov 20 '12 at 7:44












                @xiaoyi you're right, fixed it.
                – Bart Friederichs
                Nov 20 '12 at 7:45




                @xiaoyi you're right, fixed it.
                – Bart Friederichs
                Nov 20 '12 at 7:45












                Not sure how important it is, but since you're working with hex with parseInt, you probably want to use parseInt(a, 16)
                – Ian
                Nov 20 '12 at 8:00




                Not sure how important it is, but since you're working with hex with parseInt, you probably want to use parseInt(a, 16)
                – Ian
                Nov 20 '12 at 8:00












                @Ian, I tested it in the Firebug console and parseInt("0xffeb") parses correctly. When omitting the 0x, it needs the radix. To be safe, it should be added always. I updated my answer.
                – Bart Friederichs
                Nov 20 '12 at 8:04






                @Ian, I tested it in the Firebug console and parseInt("0xffeb") parses correctly. When omitting the 0x, it needs the radix. To be safe, it should be added always. I updated my answer.
                – Bart Friederichs
                Nov 20 '12 at 8:04














                True that it works without, but parseInt works on normal int strings without it as well...unless you accidentally give bad input (like expecting radix 10 parsing but providing "012" for whatever reason) and getting 10. It seems to be a browser consistency thing too. I've just found it better to always supply the radix, even if you're working on the "normal" base 10. Just wanted to point it all out :)
                – Ian
                Nov 20 '12 at 8:07






                True that it works without, but parseInt works on normal int strings without it as well...unless you accidentally give bad input (like expecting radix 10 parsing but providing "012" for whatever reason) and getting 10. It seems to be a browser consistency thing too. I've just found it better to always supply the radix, even if you're working on the "normal" base 10. Just wanted to point it all out :)
                – Ian
                Nov 20 '12 at 8:07















                9














                I came up with this



                function hexToInt(hex) {
                if (hex.length % 2 != 0) {
                hex = "0" + hex;
                }
                var num = parseInt(hex, 16);
                var maxVal = Math.pow(2, hex.length / 2 * 8);
                if (num > maxVal / 2 - 1) {
                num = num - maxVal
                }
                return num;
                }


                And usage:



                var res = hexToInt("FF"); // -1
                res = hexToInt("A"); // same as "0A", 10
                res = hexToInt("FFF"); // same as "0FFF", 4095
                res = hexToInt("FFFF"); // -1


                So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.






                share|improve this answer


























                  9














                  I came up with this



                  function hexToInt(hex) {
                  if (hex.length % 2 != 0) {
                  hex = "0" + hex;
                  }
                  var num = parseInt(hex, 16);
                  var maxVal = Math.pow(2, hex.length / 2 * 8);
                  if (num > maxVal / 2 - 1) {
                  num = num - maxVal
                  }
                  return num;
                  }


                  And usage:



                  var res = hexToInt("FF"); // -1
                  res = hexToInt("A"); // same as "0A", 10
                  res = hexToInt("FFF"); // same as "0FFF", 4095
                  res = hexToInt("FFFF"); // -1


                  So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.






                  share|improve this answer
























                    9












                    9








                    9






                    I came up with this



                    function hexToInt(hex) {
                    if (hex.length % 2 != 0) {
                    hex = "0" + hex;
                    }
                    var num = parseInt(hex, 16);
                    var maxVal = Math.pow(2, hex.length / 2 * 8);
                    if (num > maxVal / 2 - 1) {
                    num = num - maxVal
                    }
                    return num;
                    }


                    And usage:



                    var res = hexToInt("FF"); // -1
                    res = hexToInt("A"); // same as "0A", 10
                    res = hexToInt("FFF"); // same as "0FFF", 4095
                    res = hexToInt("FFFF"); // -1


                    So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.






                    share|improve this answer












                    I came up with this



                    function hexToInt(hex) {
                    if (hex.length % 2 != 0) {
                    hex = "0" + hex;
                    }
                    var num = parseInt(hex, 16);
                    var maxVal = Math.pow(2, hex.length / 2 * 8);
                    if (num > maxVal / 2 - 1) {
                    num = num - maxVal
                    }
                    return num;
                    }


                    And usage:



                    var res = hexToInt("FF"); // -1
                    res = hexToInt("A"); // same as "0A", 10
                    res = hexToInt("FFF"); // same as "0FFF", 4095
                    res = hexToInt("FFFF"); // -1


                    So basically the hex conversion range depends on hex's length, ant this is what I was looking for. Hope it helps.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 8 '16 at 14:22









                    milosmns

                    1,62021830




                    1,62021830























                        0














                        function hexToSignedInt(hex) {
                        if (hex.length % 2 != 0) {
                        hex = "0" + hex;
                        }
                        var num = parseInt(hex, 16);
                        var maxVal = Math.pow(2, hex.length / 2 * 8);
                        if (num > maxVal / 2 - 1) {
                        num = num - maxVal
                        }
                        return num;
                        }

                        function hexToUnsignedInt(hex){
                        return parseInt(hex,16);
                        }


                        the first for signed integer and
                        the second for unsigned integer






                        share|improve this answer


























                          0














                          function hexToSignedInt(hex) {
                          if (hex.length % 2 != 0) {
                          hex = "0" + hex;
                          }
                          var num = parseInt(hex, 16);
                          var maxVal = Math.pow(2, hex.length / 2 * 8);
                          if (num > maxVal / 2 - 1) {
                          num = num - maxVal
                          }
                          return num;
                          }

                          function hexToUnsignedInt(hex){
                          return parseInt(hex,16);
                          }


                          the first for signed integer and
                          the second for unsigned integer






                          share|improve this answer
























                            0












                            0








                            0






                            function hexToSignedInt(hex) {
                            if (hex.length % 2 != 0) {
                            hex = "0" + hex;
                            }
                            var num = parseInt(hex, 16);
                            var maxVal = Math.pow(2, hex.length / 2 * 8);
                            if (num > maxVal / 2 - 1) {
                            num = num - maxVal
                            }
                            return num;
                            }

                            function hexToUnsignedInt(hex){
                            return parseInt(hex,16);
                            }


                            the first for signed integer and
                            the second for unsigned integer






                            share|improve this answer












                            function hexToSignedInt(hex) {
                            if (hex.length % 2 != 0) {
                            hex = "0" + hex;
                            }
                            var num = parseInt(hex, 16);
                            var maxVal = Math.pow(2, hex.length / 2 * 8);
                            if (num > maxVal / 2 - 1) {
                            num = num - maxVal
                            }
                            return num;
                            }

                            function hexToUnsignedInt(hex){
                            return parseInt(hex,16);
                            }


                            the first for signed integer and
                            the second for unsigned integer







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 21 at 10:57









                            Al Motion

                            31




                            31























                                0














                                Based on @Bart Friederichs I've come with:



                                function HexToSignedInt(num, numSize) {
                                var val = {
                                mask: 0x8 * Math.pow(16, numSize-1), // 0x8000 if numSize = 4
                                sub: -0x1 * Math.pow(16, numSize) //-0x10000 if numSize = 4
                                }
                                if(parseInt(num, 16) & val.mask > 0) { //negative
                                return (val.sub + parseInt(num, 16))
                                }else { //positive
                                return (parseInt(num,16))
                                }
                                }


                                so now you can specify the exact lenght.



                                var numberToConvert = "CB8";
                                HexToSignedInt(numberToConvert, 3);
                                //expected output: -840





                                share|improve this answer




























                                  0














                                  Based on @Bart Friederichs I've come with:



                                  function HexToSignedInt(num, numSize) {
                                  var val = {
                                  mask: 0x8 * Math.pow(16, numSize-1), // 0x8000 if numSize = 4
                                  sub: -0x1 * Math.pow(16, numSize) //-0x10000 if numSize = 4
                                  }
                                  if(parseInt(num, 16) & val.mask > 0) { //negative
                                  return (val.sub + parseInt(num, 16))
                                  }else { //positive
                                  return (parseInt(num,16))
                                  }
                                  }


                                  so now you can specify the exact lenght.



                                  var numberToConvert = "CB8";
                                  HexToSignedInt(numberToConvert, 3);
                                  //expected output: -840





                                  share|improve this answer


























                                    0












                                    0








                                    0






                                    Based on @Bart Friederichs I've come with:



                                    function HexToSignedInt(num, numSize) {
                                    var val = {
                                    mask: 0x8 * Math.pow(16, numSize-1), // 0x8000 if numSize = 4
                                    sub: -0x1 * Math.pow(16, numSize) //-0x10000 if numSize = 4
                                    }
                                    if(parseInt(num, 16) & val.mask > 0) { //negative
                                    return (val.sub + parseInt(num, 16))
                                    }else { //positive
                                    return (parseInt(num,16))
                                    }
                                    }


                                    so now you can specify the exact lenght.



                                    var numberToConvert = "CB8";
                                    HexToSignedInt(numberToConvert, 3);
                                    //expected output: -840





                                    share|improve this answer














                                    Based on @Bart Friederichs I've come with:



                                    function HexToSignedInt(num, numSize) {
                                    var val = {
                                    mask: 0x8 * Math.pow(16, numSize-1), // 0x8000 if numSize = 4
                                    sub: -0x1 * Math.pow(16, numSize) //-0x10000 if numSize = 4
                                    }
                                    if(parseInt(num, 16) & val.mask > 0) { //negative
                                    return (val.sub + parseInt(num, 16))
                                    }else { //positive
                                    return (parseInt(num,16))
                                    }
                                    }


                                    so now you can specify the exact lenght.



                                    var numberToConvert = "CB8";
                                    HexToSignedInt(numberToConvert, 3);
                                    //expected output: -840






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 22 at 19:57

























                                    answered Nov 22 at 19:15









                                    Kostynha

                                    85




                                    85






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f13468474%2fjavascript-convert-a-hex-signed-integer-to-a-javascript-value%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Berounka

                                        Sphinx de Gizeh

                                        Different font size/position of beamer's navigation symbols template's content depending on regular/plain...