LoginSignup
7
7

More than 5 years have passed since last update.

[Python][Ruby] hex string (16 進文字列) のエンディアンをビッグエンディアンからリトルエンディアンに変更する

Last updated at Posted at 2018-02-21

ビッグエンディアンとリトルエンディアン.png

考え方

hex string は 2 文字で 1 バイトを表すので、単に文字列の並びを逆順にしてしまうと異なるバイト列になってしまう。str から bytes に変換してから逆順にすると上手くいく。

方法

Python

方法 1

import binascii

hex_be = 'f0148c'
bytes_be = binascii.unhexlify(hex_be)
bytes_le = bytes_be[::-1]
hex_le = binascii.hexlify(bytes_le).decode()
hex_le  # '8c14f0'

方法 2

@shiracamus さん、いつもコメントありがとうございます :pray:

hex_be = 'f0148c'
bytes_be = bytes.fromhex(hex_be)
bytes_le = bytes_be[::-1]
hex_le = bytes_le.hex()
hex_le  # '8c14f0'

Ruby

hex_be = 'f0148c'
bytes_be = Array(hex_be).pack('H*')
bytes_le = bytes_be.reverse
hex_le = bytes_le.unpack1('H*')
hex_le # '8c14f0'
7
7
2

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
7
7