このブログの更新は Twitterアカウント @m_hiyama で通知されます。
Follow @m_hiyama

メールでのご連絡は hiyama{at}chimaira{dot}org まで。

はじめてのメールはスパムと判定されることがあります。最初は、信頼されているドメインから差し障りのない文面を送っていただけると、スパムと判定されにくいと思います。

参照用 記事

16進数を10進数に、あるいはその逆: bashのprintf

「16進数の0xAAって、10進数だとどうなる?」とか思うことはよくありますよね*1。そんなとき、perlワンライナーで、


$ perl -e 'print hex("AA")'
170
$

とかしてました。

でも、bashを使っているならprintfというコマンド(組み込みコマンド*2)があるんですよね。


$ help printf
printf: printf [-v var] format [arguments]
printf formats and prints ARGUMENTS under control of the FORMAT. FORMAT
is a character string which contains three types of objects: plain
characters, which are simply copied to standard output, character escape
sequences which are converted and copied to the standard output, and
format specifications, each of which causes printing of the next successive
argument. In addition to the standard printf(1) formats, %b means to
expand backslash escape sequences in the corresponding argument, and %q
means to quote the argument in a way that can be reused as shell input.
If the -v option is supplied, the output is placed into the value of the
shell variable VAR rather than being sent to the standard output.

$

printfについては、「このシェル・ワンライナーがけっこう役立った: printfコマンドで超簡易テンプレート」で、テンプレートっぽい処理に使えることを紹介しました。もちろん、%d というフォーマット指定子も使えるので:


$ printf %d 0xAA
170
$

%x を使えば:


$ printf %x 170
aa
$

printfでは、\n という形の改行も使えるので、echoより便利です。


$ echo "Hello\nworld"
Hello\nworld

$ printf "Hello\nworld"
Hello
world
$

echoで \n を使いたいなら:


$ echo $'Hello\nworld'
Hello
world

$

*1:[追記]AAなら「160 + 10」と暗算だ、という話もありますけどね。暗算が辛いときの方法です。[/追記]

*2:/bin/printf のような実体もあるかも知れません。