2012년 3월 14일 수요일

[Javascript] Hex to Decimal and Decimal to Hex

Javascript 로 Hex 를 Decimal 로 변환/Decimal 을 Hex 로 변환
참고: http://javascript.about.com/library/blh2d.htm
function d2h(d) {
 return d.toString(16);
}
function h2d(h) {
 return parseInt(h,16);
}
toString() 함수는 Number 클래스에 존재하는 함수다. 아래가 더 정확하다.
function d2h(d) {
 return Number(d).toString(16);
}
padding 을 주고 싶을 수도 있다.
참고: http://www.electrictoolbox.com/pad-number-zeroes-javascript/
function pad(number, length) {
 var str = '' + number;
 while (str.length < length) {
  str = '0' + str;
 }
 return str;
}
예)
document.writeln(pad(d2h(10), 2));
결과:

댓글 없음:

댓글 쓰기