Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hex string to signed int conversion in Ruby

Tags:

ruby

How do I convert a hex strign to its 32 bit signed int equivalent in ruby? for example

a = "fb6d8cf1" #hex string
[a].pack('H*').unpack('l') #from the documentation it unpacks to its 32 bit signed int

It converts to

-242455045

But the actual answer is

-76706575 

Could you point me to what I am doing wrong?

like image 818
Pavan K Avatar asked Apr 01 '12 10:04

Pavan K


People also ask

How do I convert string to int in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.

How do you convert string to decimal in Ruby?

Converting Strings to Numbers Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.


1 Answers

Seems like you had an endian problem. This gives the desired result:

[a].pack("H*").unpack("l>")
# => [-76706575]
["038a67f90"].pack("H*").unpack("l>")
#=> [59402233]
like image 53
Michael Kohl Avatar answered Oct 28 '22 17:10

Michael Kohl