How to reverse String.unpack('H*')


#1

Hello rubyists,

I have binary numbers that through an ODBC interface are decoded with
String.unpack(‘H*’).

Let’s give an example: the number 23.

b=‘xxxx’
b[0]=23; b[1] = b[2] = b[3] = 0

b.unpack(‘I’) => [23]
b.unpack(‘H*’) => [“17000000”]

The problem: how do I convert “17000000” to 23 ?

The following works, but seems awfully complex:
fl = “17000000”
fl.unpack(‘a2a2a2a2’).collect {|x|
“0x#{x}”.hex}.pack(‘I’).unpack(‘I’)[0]

Any suggestions ?

Han H.


#2

On 5/21/06, Han H. removed_email_address@domain.invalid wrote:

The following works, but seems awfully complex:
fl = “17000000”
fl.unpack(‘a2a2a2a2’).collect {|x| “0x#{x}”.hex}.pack(‘I’).unpack(‘I’)[0]

Any suggestions ?

irb(main):001:0> [“17000000”].pack(‘H*’).unpack(‘I*’)[0]
=> 23

Ryan


#3

On 5/21/06, Ryan L. removed_email_address@domain.invalid wrote:

irb(main):001:0> [“17000000”].pack(‘H*’).unpack(‘I*’)[0]
=> 23

Ah yes, much better allready.

Thanks,

Han H.