Advertisement
PowerCell46

Decimal to binary JS

Nov 22nd, 2022
750
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function decimalToBinary(decimal) {
  2.  
  3. decimal = Number(decimal);
  4. let binaryNumber = "";
  5.  
  6. while (decimal !== 0) {
  7.  
  8. if (decimal % 2 === 0) {
  9. binaryNumber += 0;
  10. decimal = decimal / 2;
  11. } else if (decimal % 2 !== 0) {
  12. binaryNumber += 1;
  13. decimal -= 1;
  14. if (decimal === 0) {
  15. continue;
  16. }
  17. decimal = decimal / 2;
  18. }
  19. }
  20.  
  21. while (Number(binaryNumber.length) < 8) {
  22. binaryNumber += 0;
  23. }
  24.  
  25. let arrayPrint = [];
  26.  
  27. for (let index = (Number(binaryNumber.length)); index >= 0 ; index--) {
  28. arrayPrint.push(binaryNumber[index]);
  29. }
  30. console.log(arrayPrint.join(""));
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement