16進数と10進数を相互変換するフォームです。
以下の「10進数」の入力欄に10進数を入れて「変換」をクリックすると「16進数」の欄に変換結果が表示されます。同様に16進数から10進数への変換もできます。
変換方法を以下のラジオボタンで選択してください。
16進数と10進数を相互変換するフォームです。
以下の「10進数」の入力欄に10進数を入れて「変換」をクリックすると「16進数」の欄に変換結果が表示されます。同様に16進数から10進数への変換もできます。
変換方法を以下のラジオボタンで選択してください。
上のような変換フォームを作成するHTMLと、それを動かすJavascriptのコードを以下に記載します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>10進数と16進数の相互変換</title>
</head>
<style>
input,
button {
font-size: 24px;
margin-top: 8px;
}
button {
width: 200px;
}
</style>
<body>
<h1>10進数と16進数の相互変換</h1>
<p>10進数の入力欄に10進数を入れて「変換」をクリックすると、16進数の欄に変換結果が表示されます。同様に16進数から10進数への変換もできます。</p>
<p>変換方法を以下のラジオボタンで選択してください。</p>
<form>
<div>
<input type="radio" name="type" value="10to16" id="10to16" checked>
<label for="10to16">10 → 16</label>
<input type="radio" name="type" value="16to10" id="16to10">
<label for="16to10">16 → 10</label>
</div>
<div>
<label for="num10">10進数</label>
<input type="text" id="num10" value="" placeholder="255">
</div>
<div>
<label for="num16">16進数</label>
<input type="text" id="num16" value="" placeholder="FF">
</div>
<button id="convert">変換</button>
<button id="clear">消去</button>
</form>
</body>
<script>
const num10Field = document.getElementById("num10");
const num16Field = document.getElementById("num16");
const button = document.getElementById("convert");
const message = "数値を入力してください";
button.addEventListener("click", function(e) {
e.preventDefault();
const radios = document.getElementsByName("type");
const num10 = num10Field.value;
const num16 = num16Field.value;
if (radios[0].checked) {
if (num10 == "") {
num10Field.value = message;
return;
}
num16Field.value = parseInt(num10).toString(16);
} else {
if (num16 == "") {
num16Field.value = message;
return;
}
num10Field.value = parseInt(num16, 16);
}
});
document.getElementById("clear").addEventListener("click", function(e) {
e.preventDefault();
num10Field.value = "";
num16Field.value = "";
});
</script>
</html>
10進数の数値から16進数の文字列に変換するには、以下のように toString を使用します。
(10進数の数値).toString(16);
逆に、16進数の文字列(10FFなど)から10進数を得るには parseInt の第二引数に 16 を指定します。
parseInt(16進数の文字列, 16);
以上、16進数と10進数を相互変換するためのフォームと Javascript でした。
ありがとうございました^^