explain the following Perl Code? - perl

Can anybody explain the following Perl code for me, please?
I think its in Perl and I have no clue about Perl programming. Please explain what the following code does?
$t = test(10);
sub test() {
my $str = unpack("B32", pack("N",shift));
$str2 = substr($str,16,length($str));
return $str2;
}

The pack, unpack and substr functions are documented here, here and here, respectively.
pack("N"...) packs a number into a four-byte network-order representation. unpack("B32"...) unpacks this packed number as a string of bits (zeros and ones). The substr call takes the second half of this bit string (from bit 16 onwards), which represents the lower 16 bits of the original 32-bit number.
Why it does it this way is a mystery to me. A simpler and faster solution is to deal with the lower 16 bits at the outset (note the lower case "n"):
sub test($) {
return unpack("B16", pack("n",shift));
}

shift
pops the first argument to the function from the list of arguments passed
pack("N", shift)
returns a 32bit network byte order representation of that value
my $str = unpack("B32", pack("N", shift));
stores a bitstring representation (32 bits worth) of said value (i.e. a string that looks like "00010011").
The substr is buggy and should be substr($str, 16); to get the last 16 characters of the above. (or substr($str, 16, 16);.)

In addition to Marcelo's answer, the shift function takes the #_ as its default argument. #_ contains the subroutine's arguments.

pack("N", shift) takes the argument of the function (return value of shift, which works on the arguments array by default) and makes it into an integer. The unpack("B32, part then makes it into string again, of 32 bits, so a string of 0's and 1's. The substr just takes the last 16 bit-characters, in this case.

Related

Remove upfront zeros from floating point lower than 1 in Perl

I would like to normalize the variable from ie. 00000000.1, to 0.1 using Perl
my $number = 000000.1;
$number =\~ s/^0+(\.\d+)/0$1/;
Is there any other solution to normalize floats lower than 1 by removing upfront zeros than using regex?
When I try to put those kind of numbers into an example function below
test(00000000.1, 0000000.025);
sub test {
my ($a, $b) = #_;
print $a, "\n";
print $b, "\n";
print $a + $b, "\n";
}
I get
01
021
22
which is not what is expected.
A number with leading zeros is interpreted as octal, e.g. 000000.1 is 01. I presume you have a string as input, e.g. my $number = "000000.1". With this your regex is:
my $number = "000000.1";
$number =~ s/^0+(?=0\.\d+)//;
print $number;
Output:
0.1
Explanation of regex:
^0+ -- 1+ 0 digits
(?=0\.\d+) -- positive lookahead for 0. followed by digits
Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex
Simplest way, force it to be treated as a number and it will drop the leading zeros since they are meaningless for decimal numbers
my $str = '000.1';
...
my $num = 0 + $str;
An example,† to run from the command-line:
perl -wE'$n = shift; $n = 0 + $n; say $n' 000.1
Prints 0.1
Another, more "proper" way is to format that string ('000.1' and such) using sprintf. Then you do need to make a choice about precision, but that is often a good idea anyway
my $num = sprintf "%f", $str; # default precision
Or, if you know how many decimal places you want to keep
my $num = sprintf "%.3f", $str;
† The example in the question is really invalid. An unquoted string of digits which starts with a zero (077, rather than '077') would be treated as an octal number except that the decimal point (in 000.1) renders that moot as octals can't be fractional; so, Perl being Perl, it is tortured into a number somehow, but possibly yielding unintended values.
I am not sure how one could get an actual input like that. If 000.1 is read from a file or from the command-line or from STDIN ... it will be a string, an equivalent of assigning '000.1'
See Scalar value constructors in perldata, and for far more detail, perlnumber.
As others have noted, in Perl, leading zeros produce octal numbers; 10 is just a decimal number ten but 010 is equal to decimal eight. So yeah, the numbers should be in quotes for the problem to make any sense.
But the other answers don’t explain why the printed results look funny. Contrary to Peter Thoeny’s comment and zdim’s answer, there is nothing ‘invalid’ about the numbers. True, octals can’t be floating point, but Perl does not strip the . to turn 0000000.025 into 025. What happens is this:
Perl reads the run of zeros and recognises it as an octal number.
Perl reads the dot and parses it as the concatenation operator.
Perl reads 025 and again recognises it as an octal number.
Perl coerces the operands to strings, i.e. the decimal value of the numbers in string form; 0000000 is, of course, '0' and 025 is '21'.
Perl concatenates the two strings and returns the result, i.e. '021'.
And without error.
(As an exercise, you can check something like 010.025 which, for the same reason, turns into '821'.)
This is why $a and $b are each printed with a leading zero. Also note that, to evaluate $a + $b, Perl coerces the strings to numbers, but since leading zeros in strings do not produce octals, '01' + '021' is the same as '1' + '21', returning 22.

Sprintf in Perl doesn't display hexadecimal character properly

I have a code like this.
$entry = &function(); //returns a number between 0 to 20
$var = sprintf("%#.4x", $entry);
if($var=~ /$hex/)
{
//block of statements
}
$hex will be within 0x0000 ..... 0x0014. Now, when function returns from 1 to 20, $var matches $hex. (Like 0x0001 .... 0x0014)
But when $entry is 0, $var becomes 0000. But I want it to be 0x0000. Currently, I am checking if that is 0000, I am changing it through a if loop. Please let me know if that is possible in sprintf itself.
According to the documentation for sprintf:
flags
# prefix non-zero hexadecimal with "0x" or "0X"
Note that it says non-zero, so only non-zero values will be prefixed by 0x.
A simple fix is to add the prefix manually:
sprintf "0x%04x", $entry;
The doc clearly mentions that 0x is appended only for non-zero numbers when # flag is used.This makes sense since zero is zero whether it is in Octal or Hexadecimal. Hence prefixing it with 0x doesn't make sense.
Best way to handle this would be:
if($var=~ /$hex/ or !$var)
Sounds like you are doing things backwards. Wouldn't the following make more sense?
if ($entry == hex($hex))
If you want to compare numbers, compare the numbers, not their text representation.

Convert byte to sequence of bits (binary) in Perl

I've been banging my head around this question for the past few hours; there's a lot of similar questions around here, but nothing quite the same, and none of the techniques I've seen seem to be working.
I have a sequence of bytes (integers) that I've generated from input in my program - each one represent a red, green or blue color value of a pixel in a BMP image. I essentially need to extract the bitstream representation of each byte; that is, the binary sequence of that byte.
I've been using lots of different variations of pack() and unpack(), but I'm not coming out with proper results.
For instance:
sub convertToBinary {
my $str = unpack("B32", pack("N", shift));
return $str;
}
I've also tried:
my $str = unpack("b8", shift);,
my $str = unpack("B8", shift);,
my $str = unpack("b*", shift);
And numerous other variations; none of them are seem to be working. I don't feel like it should be too hard to extract the bitpattern of a byte though.. just eight '1's or '0's, right?
What am I missing here?
I think you're looking for sprintf
sub convertToBinary {
return sprintf '%08b', shift;
}
Base on a comment, you actually want to check if the least significant bit of a byteis set.
The solution depends what you mean by byte.
If you have an 8-bit character:
if (ord("\xAC") & 0x01)
If you have an 8-bit number:
if (0xAC & 0x01)
Original answer:
It sounds like you want the binary representation of a byte. The solution depends what you mean by byte.
If you have an 8-bit character:
unpack('B8', "\xAC")
sprintf('%08b', ord("\xAC"))
sprintf('%08b', unpack('C', "\xAC"))
If you have an 8-bit number:
sprintf('%08b', 0xAC)
unpack('B8', chr(0xAC))
unpack('B8', pack('C', 0xAC))
All of the above produce the string 10101100.

Perl Cryptology: Encrypting/Decrypting ASCII chracters with pack and unpack functions

I need help figuring out how these two subroutines work and what values or data structures they return. Here's a minimal representation of the code:
#!/usr/bin/perl
use strict; use warnings;
# an array of ASCII encrypted characters
my #quality = ("C~#p)eOA`/>*", "DCCec)ds~~", "*^&*"); # for instance
# input the quality
# the '#' character in front deferences the subroutine's returned array ref
my #q = #{unpack_qual_to_phred(#quality)};
print pack_phred_to_qual(\#q) . "\n";
sub unpack_qual_to_phred{
my ($qual)=#_;
my $upack_code='c' . length($qual);
my #q=unpack("$upack_code",$qual);
for(my $i=0;$i<#q;$i++){
$q[$i]-=64;
}
return(\#q);
}
sub pack_phred_to_qual{
my ($q_ref)=#_;
#q=#{$q_ref};
for(my $i=0;$i<#q;$i++){
$q[$i]+=64;
}
my $pack_code='c' . int(#q);
my $qual=pack("$pack_code",#q);
return ($qual);
}
1;
From my understanding, the unpack_qual_to_phread() subroutine apparently decrypts the ASCII character elements stored in #quality. The subroutine reads in an array containing elements of ASCII characters. Each element of the array is processed and apparently decrypted. The subroutine then returns an array ref containing elements of the decrypted array. I understand this much however I'm not really familiar with the Perl functions pack and unpack. Also I was unable to find any good examples of them online.
I think the pack_phred_to_qual subroutine converts the quality array ref back into ASCII characters and prints them.
thanks. any help or suggestions are greatly appreciated. Also if someone could provide a simple example of how Perl's pack and unpack functions work that would help too.
Calculating the length is needless. Those functions can be simplified to
sub unpack_qual_to_phred { [ map $_ - 64, unpack 'c*', $_[0] ] }
sub pack_phred_to_qual { pack 'c*', map $_ + 64, #{ $_[0] } }
In encryption terms, it's a crazy simple substitution cypher. It simply subtracts 64 from the character number of each character. It could have been written as
sub encrypt { map $_ - 64, #_ }
sub decrypt { map $_ + 64, #_ }
The pack/unpack doesn't factor in the encryption/decryption at all; it's just a way of iterating over each byte.
It is fairly simple, as packs go. Is is calling unpack("c12", "C~#p)eOA/>*)` which takes each letter in turn and finds the ascii value for that letter, and then subtracts 64 from the value (well, subtracting 64 is a post-processing step, nothing to do with pack). So letter "C" is ascii 67 and 67-64 is 3. Thus the first value out of that function is a 3. Next is "~" which is ascii 126. 126-64 is 62. Next is # which is ascii 35, and 35-64 is -29, etc.
The complete set of numbers being generated from your script is:
3,62,-29,48,-23,37,15,1,32,-17,-2,-22
The "encryption" step simply reverses this process. Adds 64 and then converts to a char.
This is not a full answer to your question, but did you read perlpacktut? Or the pack/unpack docs on perldoc? Those will probably go a long way to helping you understand.
EDIT:
Here's a simple way to think of it: say you have a 4-byte number stored in memory, 1234. If that's in a perl scalar, $num, then
pack('s*', $num)
would return
π♦
or whatever the actual internal storage value of "1234" is. So pack() treated the scalar value as a string, and turned it into the actual binary representation of the number (you see "pi-diamond" printed out, because that's the ASCII representation of that number). Conversely,
unpack('s*', "π♦")
would return the string "1234".
The unpack() part of your unpack_qual_to_phred() subroutine could be simplified to:
my #q = unpack("c12", "C~#p)e0A`/>*");
which would return a list of ASCII character pairs, each pair corresponding to a byte in the second argument.

Perl converts to int wrong but only with specific number

the following perl code converts a float number to the wrong integer number
use strict;
my $zahl =297607.22000;
$zahl=$zahl * 100;
print "$zahl\n";
my $text=sprintf ("%017d",$zahl);
print $text;
The output of this is :
29760722
00000000029760721
The thing is, you can change the given number to other numbers and it works.
Any idea what is wrong here or does Perl simply do it wrong?
Thanks for your help!
This is related to a FAQ (Why am I getting long decimals). $zahl is not rounded properly, it is rounded down to the next lower integer.
22/100 is a periodic number in binary just like 1/3 is a periodic number in decimal. It would take infinite storage to store it exactly in a floating point number.
$ perl -e'$_="297607.22000"; $_*=100; printf "%.20f\n", $_'
29760721.99999999627470970154
int and sprintf %d truncate decimals, so you end up with 29760721. print and sprintf %f round, so you can get the desired result.
$ perl -e'$_="297607.22000"; $_*=100; printf "%017.0f\n", $_'
00000000029760722
When you are doing your floating point multiplication by 100 the result will be something like 29760721.9999999963. Then when you do the %d conversion to an integer this is truncated to 29760721.
Try sprintf('%.10f', $zahl) and you should be able to see this.
You have to be really careful with floating point numbers and treating them as fixed point. Due to various conversions that may take place in the builtins, there may be times where one integer conversion is not exactly the same as another. It appears that this happens many times with x.22 numbers:
use strict;
my $n = 0;
for (0 .. 10_000_000) {
my $float = 100 * "$_.22";
my $str = "$float";
my $int = int $float;
if ($str ne $int) {
$n++;
#say "$float, $str, $int";
}
}
say "n = $n";
which prints
n = 76269
on my system.
A careful look at the Perl source would be required to see where the exact conversion difference is.
I would recommend that if you are going to be working with fixed point numbers, to convert them all to integers (using a common conversion function, preferably looking at the source numbers as strings), and then work with them all under the use integer; pragma which will disable floating point numbers.