Forum: Ruby parse hex ascii

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
3a38c3a91c2f6466e869f2df7c2f0d01?d=identicon&s=25 Mark Zvilius (zvilius)
on 2007-03-11 03:20
I want to parse a hex-ascii string into an array of numbers. For
example:

"0164" => [1,100]

Essentially I need to iterate through character pairs and use
String#hex:

"01".hex => 1
"64".hex => 100

I can do this easily enough in "C style" with an index into the string,
i.e. equivalent to a C "for" loop. But I'm interested in solutions that
are more in the "Ruby style," using an iterator.

Suggestions?
Cd3312ac93f768b1b449af457c0fca06?d=identicon&s=25 Daniel Finnie (Guest)
on 2007-03-11 03:38
(Received via mailing list)
You could do it like this:

"0164".scan(/../).collect {|x| x.hex}

Dan
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (Guest)
on 2007-03-11 10:45
(Received via mailing list)
On Sun, Mar 11, 2007 at 11:20:16AM +0900, Mark Zvilius wrote:
>
> I can do this easily enough in "C style" with an index into the string,
> i.e. equivalent to a C "for" loop. But I'm interested in solutions that
> are more in the "Ruby style," using an iterator.
>
> Suggestions?

["01FF"].pack("H*").each_byte { |b| puts b }

or:

["01FF"].pack("H*").unpack("C*").each { |b| puts b }

(the second form constructs an explicit array of Fixnums)

Regards,

Brian.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2007-03-11 12:10
(Received via mailing list)
On 11.03.2007 10:44, Brian Candler wrote:
>> "64".hex => 100
>
> ["01FF"].pack("H*").unpack("C*").each { |b| puts b }
>
> (the second form constructs an explicit array of Fixnums)

While Brian's solution is much more elegant, here's another one:

irb(main):002:0> i="0164".to_i(16)
=> 356
irb(main):003:0> a=[]
=> []
irb(main):004:0> begin; a << (i&0xFF); i/=0x100; end while i>0
=> nil
irb(main):005:0> a
=> [100, 1]

If you do not actually need the array then String#to_i might actually be
faster / easier.  But that of course depends on what you want to do with
the result.

Kind regards

  robert
This topic is locked and can not be replied to.