473,692 Members | 2,765 Online

# 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 2507

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

### Similar topics

 4 2736 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 48643 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 2167 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 2752 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 2371 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 7818 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 5224 by: vim | last post by: hello everybody Plz tell the differance between binary file and ascii file............... Thanks in advance vim 7 3109 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 2702 by: Skybuck Flying | last post by: Hello, Visual Studio .Net 2005 (Win32) Compile error: Error 1 error C2804: binary 'operator +' has too many parameters line 16 class TSkybuckInt32 { private: 0 8548 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 9090 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... 0 8970 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 6462 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 5823 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 4331 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 2989 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 2244 by: muto222 | last post by: How can i add a mobile payment intergratation into php mysql website. 3 1966 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.