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
Asked
Active
Viewed 521 times
2
-
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 Answers
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
-
No problem. And no, you're not. BTW, it did take me more than 5 minutes :-) And my first solution was overkill too. – Marc-André Lafortune Apr 12 '10 at 21:21
-
2
-
to_s produces "nibbles" (4 bit values)? I'm not a Ruby expert, but they look like just string characters (8 or 16 bit values) to me. – Ira Baxter Apr 07 '11 at 08:48
-
@Ira: Indeed, `to_s` does not produce nibbles, it just converts to a string (i.e. does the decimal expansion). It is `pack("H*")` that "converts" these characters to nibbles. HTH – Marc-André Lafortune Apr 07 '11 at 11:52