I am working on a program to convert a string to its binary representation.
I'm picking an inefficient way to do this for the sake of learning perl;
I have a subroutine to convert individual characters to 8 bit binary strings.
I am calling this subroutine inside a loop that extracts each character of a string. The binary representation of each character is then appended to an array. This array would then contain the binary representation of the input string.
My problem is, the output of the conversion subroutine within the loop includes the output from the last call to that subroutine. I can't seem to find a way to resolve this. Is this some sort of buffering issue?
Here is my code:
Expand|Select|Wrap|Line Numbers
- sub str2bin
- {
- my($tst) = @_;
- use integer;
- {
- while($tst != 0)
- {
- $str1 = $tst%2;
- $str = $str1.$str;
- $tst = $tst/2;
- }
- }
- $j = 8-length($str);
- for($i = 0;$i<$j;$i++)
- {
- $str = "0".$str;
- }
- return $str;
- }
- sub convert
- {
- my($phi) = @_;
- $len = length($phi);
- for($k = 0;$k<$len;$k++)
- {
- $new = str2bin(ord(substr($phi,$k,1)));
- @chlist = (@chlist,$new);
- }
- return @chlist;
- }
Thanks!