カテゴリー
SugiBlog Webエンジニアのためのお役立ちTips

PHPで10進数を2・8・16進数に変換

PHPで10進数から2・8・16進数へと、基数変換を行う方法をご紹介します。

まずは10進数で変換する値を宣言しておきます。

$dec = 500;

2進数に変換

書式:decbin(int $num): string

$bin = decbin($dec);
echo $bin;

出力結果は111110100となります。

8進数に変換

書式:decoct(int $num): string

$oct = decoct($dec);
echo $oct;

出力結果は764となります。

16進数に変換

書式:dechex(int $num): string

$hex = dechex($dec);
echo $hex;

出力結果は1f4となります。


今度は逆に変換してみましょう。

2進数から10進数に変換

書式:bindec(string $binary_string): int|float

$dec = bindec('111110100');
echo $dec; //500

続きを読む…»

504 views

MySQLで10進数を2・8・16進数に変換

MySQLで基数変換を行う方法をご紹介します。

2進数に変換

SELECT BIN(500);

出力結果は111110100となります。

8進数に変換

SELECT OCT(500);

出力結果は764となります。

16進数に変換

SELECT HEX(500);

出力結果は1f4となります。

CONV関数

又、CONV関数を使っても変換することが可能です。
先ほどとは逆に2進数から10進数に変換する場合等もこちらを使用します。

書式:CONV(値, 変換元の基数, 変換先の基数)

例)500を10進数から2進数に変換

SELECT CONV(500, 10, 2);

公式リファレンス
BIN関数:https://dev.mysql.com/doc/refman/5.6/ja/string-functions.html#function_bin
OCT関数:https://dev.mysql.com/doc/refman/5.6/ja/string-functions.html#function_oct
HEX関数:https://dev.mysql.com/doc/refman/5.6/ja/string-functions.html#function_hex
CONV関数:https://dev.mysql.com/doc/refman/5.6/ja/mathematical-functions.html#function_conv

945 views

JavaScriptで10進数を2・8・16進数に変換

NumberオブジェクトのtoStringメソッドを使って、基数変換を行うことができます。

まずは10進数で変換する値を宣言しておきます。

const dec = 500;

2進数に変換

const bin = dec.toString(2);
console.log(bin);

出力結果は111110100となります。

8進数に変換

const oct = dec.toString(8);
console.log(oct);

出力結果は764となります。

16進数に変換

const hex = dec.toString(16);
console.log(hex);

出力結果は1f4となります。


今度は逆の変換をしていきましょう。
各進数を10進数に変換するときはparseInt()関数を使います。

書式:parseInt(string, radix)

第1引数は文字列です。数値を指定しても文字列に変換して処理されます。
第2引数は第1引数で指定した文字列の基数を指定します。(2 <= radix <= 36

出力結果は全て500となります。

2進数を10進数に変換

const dec = parseInt('111110100', 2);
console.log(dec);

続きを読む...»

788 views