Converting Bignum into bytes

Hi all,

I'm trying to convert a variable size BigNum into a variable length byte
representation and I don't know if there exists a direct way. I'm thinking
of Array#pack and String#unpack.

Something similar to, for ex:
big = 111111111111111111111111111111111111111
bytes = [big].pack("l*")
and then
big = bytes.unpack("l*")

Regards,
Victor

I'm trying to convert a variable size BigNum into a variable length byte
representation and I don't know if there exists a direct way. I'm thinking
of Array#pack and String#unpack.

Something similar to, for ex:
big = 111111111111111111111111111111111111111
bytes = [big].pack("l*")
and then
big = bytes.unpack("l*")

#pack and #unpack won't work for Bignums, but you can operate on their
hex representations for example. The following should do it:

big = 111111111111111111111111111111111111111

bytes = big.to_s(16).unpack('H*')[0]
big2 = [bytes].pack('H*').to_i(16)
puts big == big2 # => true

Regards,
Martin

Hi Martin,

Thank you for your answer. I also thought of this solution, but a little
bit the other way around, like this:

big = 11111111111111111111111111111111111111
bytes = [big.to_s(16)].pack("H*")
=> "\x85\xBE\xC1+K\x9A@\xD8\xF4\x83\xCB\x1Cq\xC7\x1Cp"
big2 = bytes.unpack("H*")[0].to_i(16)

However...
puts big2==big #=>false

Taking a closer look...
bytes.unpack("H*")[0]
=> "85bec12b4b9a40d8f483cb1c71c71c70"
compared to
big.to_s(16)
=> "85bec12b4b9a40d8f483cb1c71c71c7"

The base 16 length representation of big is 31 whereas the unpacked string
is 32 bytes.
I wonder is this a bug?

In any case I guess the solution is to pad the big.to_s(16) String with 0
on the left side until reaching a round (as in base 2 round) number :slight_smile:

Kind regards,
Victor

Hi Victor,

Hi Martin,

Thank you for your answer. I also thought of this solution, but a little bit
the other way around, like this:

Oops, yes, that's what I actually meant, otherwise you get the bytes of the
hex string :slight_smile:

The base 16 length representation of big is 31 whereas the unpacked string
is 32 bytes.
I wonder is this a bug?

No, it's not a bug, it's just that hex mandates an even number of
characters, whereas
the textual representation of a number doesn't - but padding
appropriately to get
an even number of characters like you mentioned solves the issue.

Regards,
Martin