473,897 Members | 3,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Diggins PDP #1.2 : Binary Arithmetic Algorithms

// binary_aritmeti c.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

#ifndef BINARY_ARITHMET IC_HPP
#define BINARY_ARITHMET IC_HPP

#include <stdexcept>
#include <cassert>
#include <limits>

namespace cdiggins
{
template<class T>
T logical_xor(con st T& x, const T& y) {
return (x || y) && !(x && y);
}

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

bool full_subtractor (bool b1, bool b2, bool& borrow)
{
bool diff;
if (borrow)
{
diff = !logical_xor(b1 , b2);
borrow = !b1 || (b1 && b2);
}
else
{
diff = logical_xor(b1, b2);
borrow = !b1 && b2;
}
return diff;
}

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) == 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_full_subtr actor() {
bool borrow = false;
test(full_subtr actor(true, true, borrow) == false);
test(borrow == false);
test(full_subtr actor(true, false, borrow) == true);
test(borrow == false);
test(full_subtr actor(false, false, borrow) == false);
test(borrow == false);
test(full_subtr actor(false, true, borrow) == true);
test(borrow == true);
test(full_subtr actor(true, true, borrow) == true);
test(borrow == true);
test(full_subtr actor(false, true, borrow) == false);
test(borrow == true);
test(full_subtr actor(false, false, borrow) == true);
test(borrow == true);
test(full_subtr actor(true, false, borrow) == false);
test(borrow == false);
}

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

#endif

Jul 23 '05 #1
0 2516

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

Similar topics

4
2743
by: christopher diggins | last post by:
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...
103
48820
by: Steven T. Hatton | last post by:
§27.4.2.1.4 Type ios_base::openmode Says this about the std::ios::binary openmode flag: *binary*: perform input and output in binary mode (as opposed to text mode) And that is basically _all_ it says about it. What the heck does the binary flag mean? -- If our hypothesis is about anything and not about some one or more particular things, then our deductions constitute mathematics. Thus mathematics may be defined as the subject in...
8
2176
by: bearophileHUGS | last post by:
Hello, I have four things to ask or to suggest, sorry if they seem basic or already discussed. ------------------- I am still ignorant about Tkinter. This little program, after pressing the "Go" eats more and more RAM, is it normal? Can it be avoided? (In normal programs this is isn't a real problem). ! import Tkinter
3
2760
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...
10
2400
by: jt | last post by:
I'm needing to take a binary string start at a certain position and return a pointer from that postion to the end of the binary stirng. something like this: char bstr; char *pos; pos=mid(bstr,35); / *return a pointer of the rest of the binary string starting at element 35 */
8
7829
by: sudharsan | last post by:
please gimme the logic to merge two binary search trees?I mean which node has to be the root node of the new binary tree?? Thanks in advance
68
5297
by: vim | last post by:
hello everybody Plz tell the differance between binary file and ascii file............... Thanks in advance vim
7
3138
by: Hallvard B Furuseth | last post by:
I'm trying to clean up a program which does arithmetic on text file positions, and also reads text files in binary mode. I can't easily get rid of it all, so I'm wondering which of the following assumptions are, well, least unportable. In particular, do anyone know if there are real-life systems where the text file assumptions below don't hold? For text mode FILE*s,
8
2715
by: Skybuck Flying | last post by:
Hello, Visual Studio .Net 2005 (Win32) Compile error: Error 1 error C2804: binary 'operator +' has too many parameters <snipped> line 16 class TSkybuckInt32 { private:
0
9990
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9837
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
11250
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10939
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,...
0
9655
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8031
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
7183
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
6073
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4292
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.