-
Notifications
You must be signed in to change notification settings - Fork 75
/
smalldiv
executable file
·121 lines (84 loc) · 2.19 KB
/
smalldiv
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/perl
use Getopt::Long;
use integer;
$helpusage = "placeholder";
GetOptions ('len=s' => \$len,
'num=s' => \$num,
'den=s' => \$den,
'skip' => \$skip) || die("$helpusage");
if (!defined($len)) { $len=8; }
$LEN=$len;
$n=d2b($num); # numerator - quotient
$m=d2b($den); # denominator - divisor
printf(".i 8\n");
printf(".o 4\n");
printf(".ilb q_ff[3] q_ff[2] q_ff[1] q_ff[0] m_ff[3] m_ff[2] m_ff[1] m_ff[0]\n");
printf(".ob smallnum[3] smallnum[2] smallnum[1] smallnum[0]\n");
printf(".type fr\n");
for ($q=0; $q<16; $q++) {
for ($m=0; $m<16; $m++) {
if ($m==0) { next; }
$result=int($q/$m);
printf("%s %s %s\n",d2bl($q,4),d2bl($m,4),d2bl($result,4));
}
}
exit;
#$LEN=length($n);
$a="0"x$LEN;
$q=$n;
#printf("n=%s, m=%s\n",$n,$m);
#printf("a=%s, q=%s\n",$a,$q);
for ($i=1; $i<=$LEN; $i++) {
#printf("iteration $n:\n");
printf("$i: a=%s q=%s\n",$a,$q);
$signa = substr($a,0,1);
$a = substr($a.$q,1,$LEN); # new a with q shifted in
if ($signa==0) { $a=b2d($a)-b2d($m); }
else { $a=b2d($a)+b2d($m); }
$a=d2b($a);
$signa = substr($a,0,1);
if ($signa==0) { $q=substr($q,1,$LEN-1)."1"; }
else { $q=substr($q,1,$LEN-1)."0"; }
}
#printf("a=$a\n");
$signa = substr($a,0,1);
if ($signa==1 && !defined($skip)) {
printf("correction:\n");
$a=b2d($a)+b2d($m);
$a=d2b($a);
}
#printf("a=$a\n");
printf("%d / %d = %d R %d ",b2d($n),b2d($m),b2d($q),b2d($a));
if ($a eq $n) { printf("-> remainder equal numerator\n"); }
else { printf("\n"); }
sub b2d {
my ($v) = @_;
$v = oct("0b" . $v);
return($v);
}
sub d2b {
my ($v) = @_;
my $repeat;
$v = sprintf "%b",$v;
if (length($v)<$LEN) {
$repeat=$LEN-length($v);
$v="0"x$repeat.$v;
}
elsif (length($v)>$LEN) {
$v=substr($v,length($v)-$LEN,$LEN);
}
return($v);
}
sub d2bl {
my ($v,$LEN) = @_;
my $repeat;
$v = sprintf "%b",$v;
if (length($v)<$LEN) {
$repeat=$LEN-length($v);
$v="0"x$repeat.$v;
}
elsif (length($v)>$LEN) {
$v=substr($v,length($v)-$LEN,$LEN);
}
return($v);
}