Convert a Number to an hexadecimal String


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function toHex(number, min)
  2. {
  3. var hexes = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
  4. var hex = '';
  5. var min = min || 2;
  6. var nibble;
  7.  
  8. do
  9. {
  10. nibble = number & 0x0f;
  11. number = number >> 4;
  12. hex = hexes[nibble] + hex;
  13. }
  14. while( number );
  15.  
  16. if( hex.length < min )
  17. {
  18. hex = new Array(min-hex.length+1).join('0') + hex;
  19. }
  20.  
  21. return '0x'+hex;
  22. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.