http://www.perlmonks.org?node_id=621007


in reply to Encoding BCD

This code:

if ($test1 = $test2) { $comp = "EQUALS"; } else { $comp = "Does NOT Equal"; }

does not do what you think it does. Most likely you want to use one of the comparison operators, eq for string comparison or == for numerical comparison. Look at:

my $test1 = 123; my $test2 = 456; print "1. Test1: '$test1', test2: '$test2'\n"; if ($test1 = $test2) { print "2a. Test1: '$test1', test2: '$test2'\n"; $comp = "EQUALS"; } else { print "2b. Test1: '$test1', test2: '$test2'\n"; $comp = "Does NOT Equal"; } print "3. Test1: '$test1', test2: '$test2'\n";

I use the following to convert a BCD string to a Perl number/string:

=head2 C<decode_COMP3> Decodes a COMP3 BCD-number with trailing sign =cut sub decode_COMP3 { # Cut off the last nibble # 0C -> + # 0D -> - # 0F -> (unsigned number) my $digits = unpack "H*", $_[0]; my $sign = chop $digits; #print "$digits\n"; if ($sign eq 'D' or $sign eq 'd') { $sign = '-' } elsif ($sign eq 'C' or $sign eq 'c') { $sign = '+' } elsif ($sign eq 'F' or $sign eq 'f') { $sign = ' ' } else { $digits .= $sign; $sign = '?' }; "$sign$digits" };

In your case, maybe you want to throw away all the sign handling. The code could then be:

sub decode_BCD { unpack "H*", $_[0]; };

When debugging string packing/unpacking problems, I often write me a test suite to make sure all my assumptions about the data get documented somewhere. You might want to use something like the following:

use strict; use Test::More tests => 4; use_ok 'MyBCDDecodePackage'; is decode_BCD("\x12\x34\x56","123456"); is decode_BCD("\x00\x34\x56","003456"); is decode_BCD("\x12","12");

and then add all cases from your actual input data that you find interesting/problematic.