To and from hex nibbles

D

daniel åkerud

[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
 
P

Peña, Botp

From: daniel =E5kerud [mailto:[email protected]]=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
 
P

Peña, Botp

# 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
 

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

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,149
Latest member
Vinay Kumar Nevatia0
Top