Question

I have a binary string, say

x = "c1\x98\xCCf3\x1C\x00.\x01\xC7\x00\xC0"

(actually much longer). I need to have it represented as Bignum, for the purposes of further conversion to base-something sequences (something > 36).

x.unpack('H*')[0].to_i

yields an Integer from first bytes of the value, and not a Bignum.

Was it helpful?

Solution

There's no need to use unpack and go through an intermediate hex string representation.

To convert a binary string directly to a number (which will automatically be a Bignum as needed), you can do:

"\xc1\x98\xCC\xf3\x1C\x00".bytes.inject {|a, b| (a << 8) + b }
 => 212862017674240

OTHER TIPS

The default base for String#to_i is, of course, 10 but you're trying to convert hex so you want .to_i(16). If you don't specify the base, to_i will stop when it sees the first non-decimal value and that's where your truncation comes from.

You want to say this:

x.unpack('H*')[0].to_i(16)

For example:

>> "633198cc66331c0001c700c0633198cc66331c0001c700c063312e98cc66331c0001c700c0".to_i
=> 633198
>> "633198cc66331c0001c700c0633198cc66331c0001c700c063312e98cc66331c0001c700c0".to_i(16)
=> 49331350698902676183344474146684368690988113012187221237314170009285390086987127695278272
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top