2

Continuing with my adventure to convert COBOL to a Ruby program, I have to convert a decimal digit to a comp-3/packed decimal format. Anyone know of a simple Ruby script or gem that does this? Berns

btelles
  • 5,390
  • 7
  • 46
  • 78
  • This should take you about 5 minutes to write... – Marc-André Lafortune Apr 12 '10 at 19:23
  • Hi Mark-Andre. Do you know where I might find the algorithm, or at least an explanation of the algorithm that would help me understand how to spend those five minutes? I understand nipples (or nybbles) are involved, and a byte can have exactly 2, which means all of my digits should end up looking great! :) – btelles Apr 12 '10 at 19:55
  • I looked at http://www.3480-3590-data-conversion.com/article-packed-fields.html and answered with some code. Good luck. – Marc-André Lafortune Apr 12 '10 at 20:21
  • Actually, there's even builtin nibble packing in Ruby. Who knew. Answer updated. – Marc-André Lafortune Apr 12 '10 at 20:57

1 Answers1

4

Ruby knows how to pack nibbles, so it turns out to be quite easy:

def pack_comp(n)
  s = n.abs.to_s + (n < 0 ? "d" : "c")
  s = "0" + s if s.size.odd?
  [s].pack("H*")
end
Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166