[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

To and from hex nibbles

daniel åkerud

6/10/2008 8:38:00 AM

[Note: parts of this message were removed to make it a legal post.]

Hello, I am converting to and from hex nibbles using the code below. Is
there a smarter way for this?

To hex nibbles:
'testing 123'.scan(/./).collect { |i| i.unpack('C')[0].to_s(16) }.join
=> "74657374696e6720313233"

and back to binary:

"74657374696e6720313233".scan(/../).collect { |i| i.to_i(16) }.pack('C*')
=> "testing 123"

Thanks,

/D

2 Answers

Peña, Botp

6/10/2008 9:44:00 AM

0

From: daniel =E5kerud [mailto:daniel.akerud@gmail.com]=20
# 'testing 123'.scan(/./).collect { |i| i.unpack('C')[0].to_s(16) }.join
# =3D> "74657374696e6720313233"
# and back to binary:
# "74657374696e6720313233".scan(/../).collect { |i| i.to_i(16)=20
# }.pack('C*') # =3D> "testing 123"

s=3D'testing 123'.unpack("H*")[0]
#=3D> "74657374696e6720313233"

s.scan(/../).map{|i| i.to_i(16)}.pack("C*")
#=3D> "testing 123"

kind regards -botp

Peña, Botp

6/10/2008 9:54:00 AM

0

# s.scan(/../).map{|i| i.to_i(16)}.pack("C*")
# #=3D> "testing 123"

sorry, i missed dblack's scanf

s.scanf("%2x"*s.size).pack("C*")
#=3D> "testing 123"

kind regards -botp