この記事は?
Ruby で以下を行う方法を備忘録として残します ✍️
- 文字列を zlib で圧縮・展開する。
- バイナリ文字列を 16 進数文字列に、あるいは16 進数文字列をバイナリ文字列に変換する。
方法
require 'zlib'
string = 'ヨーヨー振りたい 🪀'
# 文字列を圧縮 → バイナリ文字列 → 16 進数文字列
binary_string = Zlib::Deflate.deflate(string, Zlib::BEST_COMPRESSION)
#=> "x\xDA{\xDC\xBC\xE2q\xF3\x9E\xC7`\xF2Y\xCF\xFA\xC7M]\x8F\e\xE7?nlQ\xF80\x7FU\x03\x00+q\x135"
hex_string = binary_string.unpack1('H*')
#=> "78da7bdcbce271f39ec760f259cffac74d5d8f1be73f6e6c51f8307f5503002b711335"
# 16 進数文字列 → バイナリ文字列 → 展開
binary_string = [hex_string].pack('H*')
#=> "x\xDA{\xDC\xBC\xE2q\xF3\x9E\xC7`\xF2Y\xCF\xFA\xC7M]\x8F\e\xE7?nlQ\xF80\x7FU\x03\x00+q\x135"
Zlib::Inflate.inflate(binary_string)
#=> "\xE3\x83\xA8\xE3\x83\xBC\xE3\x83\xA8\xE3\x83\xBC\xE6\x8C\xAF\xE3\x82\x8A\xE3\x81\x9F\xE3\x81\x84 \xF0\x9F\xAA\x80"
Zlib::Inflate.inflate(binary_string).force_encoding(Encoding::UTF_8)
#=> "ヨーヨー振りたい 🪀"
バージョン情報
$ ruby -v
ruby 3.3.4 (2024-07-09 revision be1089c8ec) [arm64-darwin22]