Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Ruby (http://www.velocityreviews.com/forums/f66-ruby.html)
-   -   Packing and unpacking unsigned integers of arbitrary size as binarystrings (http://www.velocityreviews.com/forums/t866841-packing-and-unpacking-unsigned-integers-of-arbitrary-size-as-binarystrings.html)

Aaron D. Gifford 04-07-2011 04:56 AM

Packing and unpacking unsigned integers of arbitrary size as binarystrings
 
I see there's a 'w' option to pack for packing arbitrary sized
unsigned integers in BER compressed format. However I need to
pack/unpack binary strings as simple binary byte strings.

The results of my own needs have been gemmified as the bignumpack gem.
See https://github.com/astounding/bignum.../bignumpack.rb

Are there alternatives that may be more efficient, or if I've missed
something obvious.

I resorted to splitting the binary string into 64-bit sized chunks and
using the 'Q' packing option (except where I couldn't determine
endianness, where I resorted to using the 32-bit network-order 'N'
packing option).

While I tried to be endian-architecture friendly, I don't have a
big-endian box with Ruby on it handy to test and would appreciate it
if anyone on a big-endian box would let me know if the tests fail.

Aaron out.


Brian Candler 04-07-2011 09:41 AM

Re: Packing and unpacking unsigned integers of arbitrary size asbinary strings
 
Aaron D. Gifford wrote in post #991376:
> Are there alternatives that may be more efficient, or if I've missed
> something obvious.


I'd just do this:

>> num = 12345678901234567890

=> 12345678901234567890
>> hex = num.to_s(16)

=> "ab54a98ceb1f0ad2"
>> hex.size

=> 16
>> [hex].pack("H*")

=> "\253T\251\214\353\037\n\322"

Add an extra '0' to the left of hex if it's an odd number of characters.

--
Posted via http://www.ruby-forum.com/.


Brian Candler 04-07-2011 09:43 AM

Re: Packing and unpacking unsigned integers of arbitrary size asbinary strings
 
Oh, I forgot to do the reverse:

>> bin = "\253T\251\214\353\037\n\322"

=> "\253T\251\214\353\037\n\322"
>> bin.unpack("H*").first.to_i(16)

=> 12345678901234567890

--
Posted via http://www.ruby-forum.com/.


Aaron D. Gifford 04-07-2011 04:30 PM

Re: Packing and unpacking unsigned integers of arbitrary size asbinary strings
 
Nice, using the conversion via hex string is faster for
number-to-binary-string conversion, but slower in string-to-number
conversion on my system. I think I'll update and use it for
number-to-string.

Thanks!

Aaron out.



All times are GMT. The time now is 11:48 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57