From: Ara.T.Howard@... Date: 2004-09-23T03:44:34+09:00 Subject: Re: negative numbers and binary formats On Wed, 22 Sep 2004, Paul wrote: > Im trying to take a negative integer value, convert it to its binary > equivalent, and save its hex value > > -7 -> 1111 1001 -> F9 > > > I was hoping to use sprintf, but: > > irb(main):017:0> b = sprintf("%4b" , a) > => "..1001" > irb(main):018:0> > > The .. that appear break any further processing. So my questions are: > > Why the dots, and what are they? > How do I do what Im trying to do - given my -7 in the example may be a > 1 byte, 2 byte or 4 byte value. ( Im sure its some magic with > pack....) > > Thanks > > Paul you have a couple of options: the [] method of Fixnum returns the bit: harp:~ > cat a.rb class Fixnum def to_bin packed = [self].pack 'N' n_bytes = packed.size n_bits = n_bytes * 8 s = '' n_bits.times{|bit| s << self[n_bits - bit].to_s} s end end p 42.to_bin p -7.to_bin harp:~ > ruby a.rb "00000000000000000000000000010101" "11111111111111111111111111111100" but perhaps only printf will suffice? irb(main):003:0> printf "%32.32b", -7 11111111111111111111111111111001=> nil irb(main):009:0> printf "%4.4o", -7 7771=> nil but i'm not exactly sure where you are headed with this. the '...' above is just showing you the extension of the sign bit. -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | A flower falls, even though we love it; | and a weed grows, even though we do not love it. | --Dogen ===============================================================================