0

What is the best way to get from integer number A -> binary 0xA.

Explanation on example:

  • I have [52, 49, 46] -> [00110100, 00110001, 00101110]
  • I need [0x52, 0x49, 0x46] -> [82, 73, 70] -> [01010010, 01001001, 01000110]

My solution:

var arr = [52, 49, 46] 
for(var i=0; i<arr.length; i++){
   arr[i] = parseInt("0x" + arr[i]);
}

Are there any other ways to do it?

Upgrade by Eric Dobbs:

arr = arr.map(x => parseInt(x, 16));
Denis Ross
  • 165
  • 11
  • 1
    *"...from integer number A..."* What is an "integer number A"? *"... -> binary 0xA..."* What is a "binary 0xA"? (0x is a hex prefix). Are you confusing *representation* with *value*? – T.J. Crowder May 09 '17 at 13:08
  • 2
    You can pass 16 as a second argument to parseInt: `arr = arr.map(x => parseInt(x, 16));` – Eric Dobbs May 09 '17 at 13:08
  • `(52).toString(2)` – epascarello May 09 '17 at 13:10
  • http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript – epascarello May 09 '17 at 13:11
  • Or better, be explicit about the base conversion: `parseInt(x.toString(10), 16)`. Of course you should probably just fix your data source to output the proper numbers (in the proper format, if they're literals) into that array from the beginning. – Bergi Oct 16 '17 at 22:03

1 Answers1

0

When you have a number, you can use toString(2) to get its representation (a string) in binary. Prepending a bunch of zeros and then using .slice(-8) will pad it out to eight digits. So for example:

[52, 49, 46, 0x52, 0x49, 0x46].forEach(function(num) {
  console.log(("00000000" + num.toString(2)).slice(-8));
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875