From: Warren Brown Date: 2004-09-23T04:01:55+09:00 Subject: Re: negative numbers and binary formats Paul, > 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? I'm not sure about the "why", but the "what" is fairly easy. Think of the ".." as "continue the first digit out to the left as far as you need to". For example, "%b" % -1 yields "..1", which means 1111, 11111111, 1111111111111111, or however many bits you need in your representation of -1. "%x" % -1 yields "..f", which means ff, ffff, ffffffff, or however many hex digits you need to represent -1. Does this make sense? > 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. The most straight-forward way of handling this would be to replicate the digit following the ".." as many times as you need and remove the "..". The general form of this function would be: def myformat(val,fmtstr,len) fill = "0" str = fmtstr % val if str =~ /^\.\./ str = str[2..-1] fill = str[0..0] end str.rjust(len,fill)[-len..-1] end Then myformat(-7,"%x",2) would yield "f9" and myformat(-7,"%x",4) would yield "fff9". I hope this helps. - Warren Brown