From: Mark Hubbart Date: 2004-09-23T05:26:58+09:00 Subject: Re: negative numbers and binary formats On Sep 22, 2004, at 11:14 AM, 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....) well, if all you need is the hex part, here you go: class Integer def internal_hex # choose a packing strategy case self when (-128..127) # char [self].pack('c').unpack('C').first.to_s 16 when (-32768..32767) # short [self].pack('s').unpack('S').first.to_s 16 when (-2147483648..2147483647) # long [self].pack('l').unpack('L').first.to_s 16 else "too big!" # :) end end end -7.internal_hex #=>"f9" the hex string will be in big-endian (network) byte-order; that's the way to_s(16) does it. cheers Mark > > Thanks > > Paul >