Konwertuj ciąg znaków z kodami ASCII hex na znaki
Mam łańcuch zawierający wartości kodu szesnastkowego znaków ASCII, np. "666f6f626172"
. Chcę przekonwertować go na odpowiedni łańcuch ("foobar"
).
To działa, ale brzydkie:
"666f6f626172".scan(/../).map(&:hex).map(&:chr).join # => "foobar"
Czy jest lepszy (bardziej zwięzły) sposób? Czy może być jakoś pomocna?
20
Author: undur_gongor, 2014-04-09
2 answers
Możesz użyć Array#pack
:
["666f6f626172"].pack('H*')
#=> "foobar"
H
jest dyrektywą Dla ciągu sześciokątnego (high nibble first).
40
Author: Stefan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-09 10:07:47
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-09 10:07:47
Stefan dał radę, ale oto alternatywa, którą możesz chcieć schować w innym czasie i miejscu:
"666f6f626172".gsub(/../) { |pair| pair.hex.chr } # => "foobar"
16
Author: Cary Swoveland,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-09 17:19:12
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-09 17:19:12