LoginSignup
2
2

More than 5 years have passed since last update.

bash で hex string のエンディアンを変換する

Last updated at Posted at 2019-02-04

概要

以前 [Python][Ruby] hex string (16 進文字列) のエンディアンをビッグエンディアンからリトルエンディアンに変更する という記事を書いたが、これと同じことを bash のワンライナーでやりたい。ただし厳密に行うのは難しいので、単純に文字列を 2 文字づつに分割して順番を逆にするという方針を取る。

方法

$ echo 1234abcd | fold -w2 | tail -r | tr -d '\n'
cdab3412

変換の流れは次の通り。

1234abcd

🔽

12
34
ab
cd

🔽

cd
ab
34
12

🔽

cdab3412

おまけ

[Python][Ruby] hex string (16 進文字列) のエンディアンをビッグエンディアンからリトルエンディアンに変更する で紹介した方法をワンライナーで実行する。

Ruby

$ echo 1234abcd | ruby -e "puts(Array(gets.chomp).pack('H*').reverse.unpack1('H*'))"
cdab3412

Python

$ echo 1234abcd | python -c "import sys; print(bytes.fromhex(sys.stdin.readline().rstrip())[::-1].hex())"
cdab3412
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2