How to add the binary representation of a number to array in JavaScript

1 Answer

0 votes
function toBinArray(arr, n) {
    for (let i = 0; i < 8; i++) {
        arr[i] = n & 0x80 ? '1' : '0';
        n <<= 1;
    }
}
   
const value = 12; 
const arr = [0,0,0,0,0,0,0,0];
  
toBinArray(arr, value);
   
console.log(value + ' = ' + arr);
   
  
  
    
/*
run:
   
"12 = 0,0,0,0,1,1,0,0"
    
*/

 



answered May 27, 2022 by avibootz
edited May 27, 2022 by avibootz
...