473,769 Members | 3,350 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Diggins PDP #1 : Binary Arithmetic Algorithms (division / multiplication / full_adder )

Welcome to the first installment of the Diggins Public Domain Posts (PDP).

There is a significant dearth of good public domain C++ code. All of it
seems to come with one kind of a license or another, and even though I
understand the motivations, I believe code is like mathematics and no one
can really own it. Rather than stand on a pulpit, or debate the
philosophical merits of the various licenses, I have decided instead to post
as much code into the public domain as I possibly can in a series of posts
to comp.lang.c++ called the Diggins Public Domain Posts. I hope you find it
useful, educational or at the very least entertaining. I welcome any
comments or suggestions but I am especially keen to see posted improvements
to the code I share. Enjoy!

==

Diggins PDP #1
Binary Arithmetic Algorithms

The following are basic algorithms for binary addition, multiplication and
division. The algorithms were chosen for simplicity instead of efficiency.
This code is useful for implementing new kinds of integers and are forming
the basis of my upcoming fixed_int and big_int classes.

// public domain by Christopher Diggins

#include <stdexcept>

namespace cdiggins
{
bool full_adder(bool b1, bool b2, bool& carry)
{
bool sum = (b1 ^ b2) ^ carry;
carry = (b1 && b2) || (b1 && carry) || (b2 && carry);
return sum;
}

template<typena me T>
T multiply(T x, T y)
{
T ret = 0;
while (y > 0)
{
if (y & 1) {
ret += x;
}
y >>= 1;
x <<= 1;
}
return ret;
}

template<typena me T>
void divide(T x, T y, T& q, T& r)
{
if (y == 0) {
throw std::domain_err or("division by zero undefined");
}
if (x == 0) {
q = 0;
r = 0;
return;
}
if (x <= y) {
if (x == y) {
q = 1;
r = 0;
return;
}
else {
q = 0;
r = x;
return;
}
}
q = 0;
r = x;
int n=1;
while (y < x) {
y <<= 1;
n++;
}
while (n--) {
q <<= 1;
if (y <= r) {
q |= 1;
r = r - y;
}
y >>= 1;
}
}

template<typena me T>
T divide_quotient (const T& x, const T& y) {
T q;
T r;
divide(x, y, q, r);
return q;
}

template<typena me T>
T divide_remainde r(const T& x, const T& y) {
T q;
T r;
divide(x, y, q, r);
return r;
}
}

namespace binary_arithmet ic_test
{
using namespace cdiggins;

void test(bool b) {
if (!b) {
throw std::runtime_er ror("test failed");
}
}

void test_divide() {
for (int i=0; i < 255; i++) {
for (int j=1; j < 255; j++) {
test(divide_quo tient(i, j) == i / j);
test(divide_rem ainder(i, j) == i % j);
}
}
}

void test_multiply() {
for (int i=0; i < 255; i++) {
for (int j=0; j < 255; j++) {
test(multiply(i , j) == i * j);
}
}
}

void test_full_adder () {
bool carry = true;
test(full_adder (true, true, carry) == true);
test(carry == true);
test(full_adder (true, false, carry) == false);
test(carry == true);
test(full_adder (false, true, carry) == false);
test(carry == true);
test(full_adder (false, false, carry) == true);
test(carry == false);
test(full_adder (true, false, carry) == true);
test(carry == false);
test(full_adder (false, true, carry) == true);
test(carry == false);
test(full_adder (true, true, carry) == false);
test(carry == true);
}

void test_main()
{
test_divide();
test_multiply() ;
test_full_adder ();
}
}

--
Christopher Diggins
http://www.cdiggins.com
Jul 23 '05 #1
4 2739
pjp
christopher diggins wrote:
Welcome to the first installment of the Diggins Public Domain Posts (PDP).
There is a significant dearth of good public domain C++ code. All of it seems to come with one kind of a license or another, and even though I understand the motivations, I believe code is like mathematics and no one can really own it.
Literature is like letters too, but it has a perceived worth that's
worth honoring if you combine those letters in entertaining or
informative ways...
Rather than stand on a pulpit, or debate the
philosophical merits of the various licenses, I have decided instead to post as much code into the public domain as I possibly can in a series of posts to comp.lang.c++ called the Diggins Public Domain Posts. I hope you find it useful, educational or at the very least entertaining. I welcome any
comments or suggestions but I am especially keen to see posted improvements to the code I share. Enjoy!


I admire your idealism, but...

I found several obvious bugs in a one-minute sweep through the code.
Mostly they're the kind of bugs novices introduce. Several result in
infinite loops for seemingly innocuous inputs. And those are the kind
of bugs that eat up *lots* of your time; hence they cost you way more
money than you save by getting something for free.

Useful, educational, and/or entertaining? Only as a cautionary tale.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com

Jul 23 '05 #2
<pj*@plauger.co m> wrote in message
news:11******** *************@g 44g2000cwa.goog legroups.com...
christopher diggins wrote:

Literature is like letters too, but it has a perceived worth that's
worth honoring if you combine those letters in entertaining or
informative ways...
This is a valid point though I don't agree fully with the analogy. I should
probably steer clear from the debate, because my views are bound to be
unpopular and controversial. I just would like to encourage contributions to
the public domain.
I admire your idealism, but...

I found several obvious bugs in a one-minute sweep through the code.
Mostly they're the kind of bugs novices introduce. Several result in
infinite loops for seemingly innocuous inputs.
If you would share any of the bugs with me (or at the very least some
examples of broken input), I would be most appreciative. One big mistake I
made is that I should have made explicit that the multiplication / division
algorithms were only intended for positive integer values.
And those are the kind
of bugs that eat up *lots* of your time; hence they cost you way more
money than you save by getting something for free.
Sure, but hopefully people will point these bugs out, and then this free
code can be improved, and then perhaps become truly useful.
Useful, educational, and/or entertaining? Only as a cautionary tale.


A cautionary tale against what?

Thank you for responding to the post. I am very glad it at least provoked
some kind of reaction.

--
Christopher Diggins
Jul 23 '05 #3
// The Diggins PDP (Public Domain Post) #1.1
// Public Domain code by Christopher Diggins, May 22, 2005
// corrected division bugs posted for version 1.0 on May 21
// thanks to P.J. Plauger for pointing out errors
//
// Description:
// - simple multiplication algorithm of arbitrary unsigned integers using
shifts and addition
// - simple division algorithm of arbitrary unsigned integers using shifts
and subtraction
// - significant digit counting function
// - full adder logic gate emulation function

#ifndef BINARY_ARITHMET IC_HPP
#define BINARY_ARITHMET IC_HPP

#include <stdexcept>
#include <cassert>

namespace cdiggins
{
bool full_adder(bool b1, bool b2, bool& carry)
{
bool sum = (b1 ^ b2) ^ carry;
carry = (b1 && b2) || (b1 && carry) || (b2 && carry);
return sum;
}

template<typena me T>
unsigned int count_significa nt_digits(T x) {
unsigned int n = 0;
while (x > 0) {
++n;
x >>= 1;
}
return n;
}

template<typena me T>
T multiply(T x, T y)
{
// this multiply accepts only non-negative integer values
assert(x >= 0);
assert(y >= 0);
T ret = 0;
while (y > 0)
{
if (y & 1) {
ret += x;
}
y >>= 1;
x <<= 1;
}
return ret;
}

template<typena me T>
void divide(T x, T y, T& q, T& r)
{
// this divide accepts only non-negative integer values
assert(x >= 0);
assert(y >= 0);
if (y == 0) {
throw std::domain_err or("division by zero undefined");
}
if (x == 0) {
q = 0;
r = 0;
return;
}
if (y == x) {
q = 1;
r = 0;
return;
}

q = 0;
r = x;

if (y > x) {
return;
}

// count significant digits in divisor and dividend
unsigned int sig_x = count_significa nt_digits(x);
unsigned int sig_y = count_significa nt_digits(y);

// check against my own stupidity
assert(sig_x >= sig_y);

// align the divisor with the dividend
unsigned int n = (sig_x - sig_y);
y <<= n;

n += 1; // make sure the loop executes the right number of times

// long division algorithm, shift and subtract
while (n--)
{
q <<= 1; // shift the quotient to the left
if (y <= r)
{
q |= 1; // add a new digit to quotient
r = r - y; // subtract from the remained
}
y >>= 1; // shift the divisor to the right
}
}

template<typena me T>
T divide_quotient (const T& x, const T& y) {
T q;
T r;
divide(x, y, q, r);
return q;
}

template<typena me T>
T divide_remainde r(const T& x, const T& y) {
T q;
T r;
divide(x, y, q, r);
return r;
}
}

namespace binary_arithmet ic_test
{
using namespace cdiggins;

void test(bool b) {
if (!b) {
throw std::runtime_er ror("test failed");
}
}

void test_divide() {
for (unsigned char i=0; i < 0xFF; i++) {
for (unsigned char j=1; j < 0xFF; j++) {
test(divide_quo tient(i, j) == i / j);
test(divide_rem ainder(i, j) == i % j);
}
}
}

void test_multiply() {
for (int i=0; i < 0xFF; i++) {
for (int j=0; j < 0xFF; j++) {
test(multiply(i , j) == i * j);
}
}
}

void test_full_adder () {
bool carry = true;
test(full_adder (true, true, carry) == true);
test(carry == true);
test(full_adder (true, false, carry) == false);
test(carry == true);
test(full_adder (false, true, carry) == false);
test(carry == true);
test(full_adder (false, false, carry) == true);
test(carry == false);
test(full_adder (true, false, carry) == true);
test(carry == false);
test(full_adder (false, true, carry) == true);
test(carry == false);
test(full_adder (true, true, carry) == false);
test(carry == true);
}

void test_main()
{
test_divide();
test_multiply() ;
test_full_adder ();
}
}

#endif
Jul 23 '05 #4
> I found several obvious bugs in a one-minute sweep through the code.
Mostly they're the kind of bugs novices introduce. Several result in
infinite loops for seemingly innocuous inputs. And those are the kind
of bugs that eat up *lots* of your time; hence they cost you way more
money than you save by getting something for free.


I think I found the bugs you referred to. I have posted a new version.
Thanks for pointing out that I had errors, I really appreciate it, and I
credit you in the new version I posted.

I think however you were trying to make the point that free code can be
expensive because quality can be so hard to assure. I fully agree, and I
think this is why there will always be a market for commercial code.

I should point out that my qualms aren't with commercial code, but rather
with the various "free" licenses. The idea of restricting something and
calling it free is offensive to me. My goal is to combat this by simply
trying to contribute to the public domain code base as much as I can, and
perhaps encourage others to contribute as well.

Maybe I misread your tone, but I would have thought that commercial library
authours such as yourself would be more receptive and supportive of the idea
of public domain code over free but licensed code, because there is
absolutely no restriction over the usage in commercial libraries.

Christopher Diggins

Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
1895
by: Marc Schellens | last post by:
I have a: vector<A> V; an A* a; which might point to one element of V.
1
4447
by: Sherrie Laraurens | last post by:
Hi, I'm after a good "free" galois field library in c++, something where I can do polynomial operations such as add,sub,mul and div and may be even remainder. does anyone have any experience with such libraries? cheers
1
2828
by: akickdoe22 | last post by:
Please help me finish this program. i have completed the addition and the subtraction parts, but i am stuck on the multiplication and division. any suggestions, hints, code, anyhting. it's not a true large int calculator, the numbers entered are at max 100 intergers. CODE SO FAR: #include<iostream> //libraries limited to #include<string> using namespace std;
0
2509
by: christopher diggins | last post by:
// binary_aritmetic.hpp // Diggins PDP (Public Domain Post) #1.2 // by Christopher Diggins, May 24, 2005 // // Comment: // Provides several algorithms for unsigned binary arithmetic // // Changes: // Now includes a full_subtractor
0
1082
by: christopher diggins | last post by:
// big_int.hpp // The Diggins PDP (Public Domain Post) #3 // Public Domain code by Christopher Diggins, May 22, 2005 // // Description: // A naively implemented unsigned integer type for arbitrarily large // values. Implemented using vector<bool> #ifndef BIG_INT_HPP #define BIG_INT_HPP
3
2757
by: ruben.de.visscher | last post by:
I am trying to write a program that encrypts 8-bit plaintext using a 10-bit key. To generate subkeys, and for other things, i will need to be able to perform permutations on binary strings for example: if k1k2k3k4k5k6k7k8k9k10 represents all ten digits of the key, the outpur of the permutation should be like this: k3k5k2k7k4k10k1k9k8k6 . I am new to operations on binary strings and i don't really know how to implement this as...
27
2055
by: jacob navia | last post by:
As Richard Bos rightly pointed out, I had left in my classification of types the C99 types Complex and boolean. Here is a new classification. Those are not mentioned in the classification of Plauger and Brody, probably because their work predates C99. Since there are no examples of this in the literature (known to me) please take a look. Thanks
13
7125
by: jamesonang | last post by:
Supposed unsigned int(32 bits) is the largest number that computer can represent with a single variable. Now, i have a big integer ( less than 64 bit, but great than 32 bit) . i represent it by this way: unsigned int dividend : divident store low 32 bits of big integer, dividend store high 32 bits of big integer.
16
5310
by: spl | last post by:
To increase the performance, how to change the / operator with bitwise operators? for ex: 25/5, 225/25 or 25/3 or any division, but I am not bothered of any remainder.
0
9424
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10000
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.