Skip to content

Instantly share code, notes, and snippets.

@bjschafer
Created March 9, 2014 04:55
Show Gist options
  • Save bjschafer/9443087 to your computer and use it in GitHub Desktop.
Save bjschafer/9443087 to your computer and use it in GitHub Desktop.
32 bit Ripple Carry Adder in C
/*
* adder.c
*
* Created on: Mar 8, 2014
* Author: braxton
*/
#include <stdio.h>
/*
* Gets bit i of a.
*
* Returns 0 or 1, whichever the bit i is.
*/
int getBit(int a, int i)
{
return ((a & (1 << i)) >> i);
}
/*
* Adds bits a and b, taking into account the carry.
*/
int sum(carry_in, a, b)
{
return ((carry_in ^ a) ^ b);
}
/*
* Figures out what the carry-over is.
*/
int carry(carry_in, a, b)
{
return (carry_in & a) & b;
}
/*
* Sets bit i of result to be s, either 0 or 1.
*/
int setBit(result, i, s)
{
if (s == 1)
return result | (1 << i);
return result & ~(1 << i);
}
int main()
{
unsigned int x, y;
scanf("%d %d", &x, &y);
unsigned int result = 0;
unsigned int carry_in = 0;
unsigned int i = 0;
unsigned int a = 0;
unsigned int b = 0;
for (i = 0; i < 32; i++) // probably can't use the increment op
{
a = getBit(x, i);
b = getBit(y, i);
unsigned int s = sum(carry_in, a, b);
unsigned int carry_out = carry(carry_in, a, b);
result = setBit(result, i, s);
carry_in = carry_out;
}
if (carry_in > 0)
printf("\n overflow has occurred, result incorrect\n");
printf("%#x %d\n", result, result);
return 0;
}
@rlefko
Copy link

rlefko commented May 28, 2020

Just casually came across this, carry logic should be '(carry_in & (a ^ b)) | (a & b)' and scanf should use '%u' (for unsigned ints) instead of '%d' (for signed ints).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment