Last active
October 6, 2021 10:11
-
-
Save ljmccarthy/c2511b8255ec1d6484b757ec7f651406 to your computer and use it in GitHub Desktop.
8-bit bitwise addition (full adder) implemented using only bitwise operations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 8-bit bitwise addition (full adder) implemented using only bitwise operations. | |
* Luke McCarthy 2021-10-06 | |
*/ | |
#include <assert.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
static uint8_t carry(uint8_t A, uint8_t B, uint8_t C) | |
{ | |
return (A & B) | (B & C) | (C & A); | |
} | |
static uint8_t bitwise_add(uint8_t A, uint8_t B) | |
{ | |
uint8_t R, C; | |
R = (A & 0x01) ^ (B & 0x01); | |
C = carry(A & 0x01, B & 0x01, 0); | |
R |= (A & 0x02) ^ (B & 0x02) ^ ((C & 0x01) << 1); | |
C |= carry(A & 0x02, B & 0x02, (C & 0x01) << 1); | |
R |= (A & 0x04) ^ (B & 0x04) ^ ((C & 0x02) << 1); | |
C |= carry(A & 0x04, B & 0x04, (C & 0x02) << 1); | |
R |= (A & 0x08) ^ (B & 0x08) ^ ((C & 0x04) << 1); | |
C |= carry(A & 0x08, B & 0x08, (C & 0x04) << 1); | |
R |= (A & 0x10) ^ (B & 0x10) ^ ((C & 0x08) << 1); | |
C |= carry(A & 0x10, B & 0x10, (C & 0x08) << 1); | |
R |= (A & 0x20) ^ (B & 0x20) ^ ((C & 0x10) << 1); | |
C |= carry(A & 0x20, B & 0x20, (C & 0x10) << 1); | |
R |= (A & 0x40) ^ (B & 0x40) ^ ((C & 0x20) << 1); | |
C |= carry(A & 0x40, B & 0x40, (C & 0x20) << 1); | |
R |= (A & 0x80) ^ (B & 0x80) ^ ((C & 0x40) << 1); | |
C |= carry(A & 0x80, B & 0x80, (C & 0x40) << 1); | |
return R; | |
} | |
int main() | |
{ | |
for (uint16_t A = 0; A < 256; A++) { | |
for (uint16_t B = 0; B < 256; B++) { | |
printf("%u + %u = %u\n", A, B, bitwise_add(A, B)); | |
assert(bitwise_add(A, B) == ((A + B) & 0xFF)); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment