in reply to Re: Testing & Using Bits
in thread Testing & Using Bits

Your code works here:

my $bytes = 0x123456; print join(" ", map { sprintf "%#02x", $_ } unpack("C*",pack("L",0x123 +45678))), "\n"; print join(" ", map { sprintf "%#02x", $_ } unpack("C*",pack("L",$byte +s))), "\n"; #output: #0x78 0x56 0x34 0x12 #0x56 0x34 0x12 00

What did you expect it to do?

Replies are listed 'Best First'.
Re^3: Testing & Using Bits
by Aim9b (Monk) on May 31, 2007 at 18:34 UTC
    That's exactly what I expected. I'll recheck my code, but I was getting all zeroes. I even cut/pasted the line & THEN substituted the scalar for the string. Also where can I fine the doc on the sprintf codes %#02x, etc. Thanks.
      %#02x means:

      • % A format code
      • # prefix with "0x"
      • 02 2 digits wide, padded with a leading zero if necessary
      • x hexadecimal

      You can read the full documentation here.

      OK, I guess there's just no getting around it... ;-) Here's my code...
      # !perl DebugBCD.pl open (inFILE, "<C:/Dev/Perl_Dev/ItemExp/TESTFILE.DAT") || die "Cannot open file\n"; # The first 6 bytes of my test file contain the 12 digit UPC Barcode 1 +23456789910 binmode (inFILE); seek (inFILE,0,0); read (inFILE,$inBuf,6); print "Len=".length($inBuf)." Raw Data = $inBuf \n"; # This prints t +he graphics $Test = DecodeBCD($inBuf); print $Test; # This prints 48 48 52 48 I expected + 1 2 3 4 close inFile; sub DecodeBCD { my ($i,@lo,@hi,$Byte,$Bits,@pairs); my $Hi,$Low; my $LoMask = 15; my $HiMask = 240; my $Zone = 0x30; for ($i = 0; $i < 2; $i++) { $Byte = substr($_[0],$i,1); $lo[$i] = ($Byte & $LoMask) | $Zone; # These OR statement +s seem to $hi[$i] = (($Byte & $HiMask) >> 4) | $Zone; # result in JUST the + $Zone piece, $pairs[$i] = join("",$lo[$i],$hi[$i]); # Implying that the +& result is Zero. print "\nLo $i=".$lo[$i]." Hi $i=".$hi[$i]." $pairs[$i]\n +"; } print "(@pairs)\n"; chomp ($Dummy = <STDIN>); join('',@pairs); }
      Please try to keep the laughter to a dull roar.
        After

        $Byte = substr($_[0],$i,1);

        $Byte will contain a single character, but you want the ASCII code of that character. So, try:

        $Byte = ord substr($_[0],$i,1);

        I think:)