Posted By

jatkins on 02/23/15


Tagged

number numbers hex decimal Converter hexadecimal dec


Versions (?)

Decimal to hexadecimal converter


 / Published in: JavaScript
 

Released into the public domain by Josh Atkins (2015).

Per this StackOverflow answer, just use (someDecNumber).toString(16) to convert to hex and parseInt(someHexNumber, 16) to convert back.

  1. function integerDecimalToBinary(decValue) {
  2. var binaryValue = '', integerResult = decValue;
  3.  
  4. do {
  5. binaryValue = integerResult % 2 + binaryValue;
  6. integerResult = Math.floor(integerResult / 2);
  7. } while(integerResult != 0)
  8.  
  9. return binaryValue;
  10. }
  11.  
  12. var binToHexTable = {
  13. '0000': 0,
  14. '0001': 1,
  15. '0010': 2,
  16. '0011': 3,
  17. '0100': 4,
  18. '0101': 5,
  19. '0110': 6,
  20. '0111': 7,
  21. '1000': 8,
  22. '1001': 9,
  23. '1010': 'A',
  24. '1011': 'B',
  25. '1100': 'C',
  26. '1101': 'D',
  27. '1110': 'E',
  28. '1111': 'F'
  29. };
  30.  
  31. function decToHex(decValue) {
  32. var binValue = integerDecimalToBinary(decValue),
  33. groupsOfFour = [];
  34.  
  35. for(var charIndex = binValue.length - 1, charsOutOfFour = 0, fourChars = ''; charIndex >= 0; charIndex--) {
  36. fourChars = binValue.charAt(charIndex) + fourChars;
  37.  
  38. if(charsOutOfFour == 3) {
  39. groupsOfFour.push(fourChars);
  40. charsOutOfFour = 0;
  41. fourChars = '';
  42. }
  43. else {
  44. charsOutOfFour++;
  45. }
  46. }
  47.  
  48. if(fourChars != '' && fourChars.length < 4) {
  49. var numberOfEmptyChars = 4 - fourChars.length;
  50. for(var charIndex = 0; charIndex < numberOfEmptyChars; charIndex++) {
  51. fourChars = '0' + fourChars;
  52. }
  53. groupsOfFour.push(fourChars);
  54. }
  55.  
  56. var hexValue = '';
  57. for(var groupIndex = 0; groupIndex < groupsOfFour.length; groupIndex++) {
  58. hexValue = binToHexTable[groupsOfFour[groupIndex]] + hexValue;
  59. }
  60.  
  61. return hexValue;
  62. }

Report this snippet  

You need to login to post a comment.