forked from trizen/perl-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
general_binary_multiplier.pl
executable file
·51 lines (41 loc) · 1.07 KB
/
general_binary_multiplier.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/perl
# Author: Daniel "Trizen" Șuteu
# License: GPLv3
# Date: 07 August 2015
# Website: https://github.com/trizen
# A general binary multiplier.
# Derived from: https://en.wikipedia.org/wiki/Binary_multiplier#A_more_advanced_approach:_an_unsigned_example
use 5.010;
use strict;
use integer;
use warnings;
my $a = 4253;
my $b = 7149;
my @a = reverse(split(//, sprintf("%b", $a)));
my @b = split(//, sprintf("%b", $b));
say @a;
say @b;
say $a * $b;
my @p = (0) x (@a + @b);
my $k = 0;
foreach my $i (@a) {
if ($i) {
say @p;
my $carry = 0;
foreach my $j (0 .. $#b) {
my $add = $b[$#b - $j] + $p[$#p - $j - $k] + $carry;
$p[$#p - $j - $k] = $add % 2;
$carry = $add / 2;
}
if ($carry) {
foreach my $j ($#b + 1 .. $#p) {
my $add = $carry + $p[$#p - $j - $k];
$p[$#p - $j - $k] = $add % 2;
$carry = ($add / 2) || last;
}
}
}
++$k;
}
say @p;
say unpack("N", pack("B32", substr("0" x 32 . join('', @p), -32)));