Hello Monks,
Update: Title update from (How to convert an integer 8bit long to binary and vice versa) to (pack and unpack with 8 bit integers).
Lately I have been asking way too many questions, apologies for that. Although that I thought that I was starting to get the conversion process of decimal to binary and binary to decimal, I got stack again.
I want to convert an integer 8 bit long with template format "i" to binary and then convert it pack to decimal with the same format "i". I want to complete the process using pack and unpack.
I have been experimenting with a sample of code. I can not figure it out why is not working properly.
Sample of code:
#!/usr/bin/perl use strict; use warnings; sub dec2bin { my $bits = shift; my $size = shift; my $template = shift; my $str = unpack("B$size", pack($template, $bits)); return $str; } sub bin2dec { my $bits = shift; my $size = shift; my $template = shift; my $substr = substr("0" x $size . $bits , -$size); print "Substring: ".$substr."\n"; my $pack = pack("B$size", $substr); print "Pack: ".$pack."\n"; my $unpack = unpack($template, $pack); return $unpack; } my $int2bin = dec2bin( 3 , 8 , "i" ); print "Int2bin: ".$int2bin."\n"; my $binary2int = bin2dec( $int2bin , 8 , "i" ); print "Decimal from binary: ".$binary2int."\n"; __END__ Int2bin: 00000011 Substring: 00000011 Pack: Use of uninitialized value $binary2int in concatenation (.) or string +at test.pl line 32. Decimal from binary:
I have broken down the process into pieces in order to detect the error. It seems the error comes from the pack process.
So at this point I can not understand why. I have found a way to by avoid the error by modifying the $template on the sub bin2dec process from "i" (intiger) to "c" (8 bit character). By doing so I get the correct output, but since I am defining B8 I should not have a problem with the unpack process.
So can someone help me understand where I am going wrong, and how to fix my problem?
Thanks in advance for everyone's time and effort to assist me.
In reply to pack and unpack with 8 bit integers by thanos1983
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |