parse hex ascii

M

Mark Zvilius

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

Brian Candler

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?

["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.
 
R

Robert Klemme

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?

["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)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top