[sourcecode language="c"]
/***********************************************************************
Add two binary (32 bits) and diaplay in binary (32 bits) with memory utilize
Coded by Md. Mahedi Azad and presented by www.insafeta.com
*************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_LINE_LEN 64
typedef enum { false = 0, true } bool;
char *getStr(const char *prompt, char *str, size_t len);
bool isValidBinaryStr(const char *);
void binAdd(const char *, const char *, char *);
const char *firstNonZero(const char *);
char A[MAX_LINE_LEN], Aprompt[MAX_LINE_LEN];
char B[MAX_LINE_LEN], Bprompt[MAX_LINE_LEN];
char C[MAX_LINE_LEN];
const size_t bitsPerInt = sizeof(int) * CHAR_BIT;
int main(int argc, char *argv[]) {
const char *a, *b, *c;
sprintf(Aprompt, "Enter up to %d 1s and 0s for A:", bitsPerInt);
sprintf(Bprompt, "Enter up to %d 1s and 0s for B:", bitsPerInt);
/* "Unlimited input and add" */
while (1) {
do {
getStr(Aprompt, A, bitsPerInt);
} while (isValidBinaryStr(A) == false);
do {
getStr(Bprompt, B, bitsPerInt);
} while (isValidBinaryStr(B) == false);
binAdd(A, B, C);
printf("%s + %s = %s\n\n",
(strlen(a = firstNonZero(A)) > 0) ? a : "0",
(strlen(b = firstNonZero(B)) > 0) ? b : "0",
(strlen(c = firstNonZero(C)) > 0) ? c : "0");
}
return 0;
}
/* "binary" addition: A + B = C, ignore carry out of MSB */
void binAdd(const char *A, const char *B, char *C) {
char *a = calloc(bitsPerInt + 1, sizeof(char)),
*b = calloc(bitsPerInt + 1, sizeof(char)), aBit, bBit, cBit;
int i, carry = 0;
/* pad with leading zeros */
memset(a, '0', bitsPerInt);
memset(b, '0', bitsPerInt);
memcpy(a + bitsPerInt - strlen(A), A, strlen(A));
memcpy(b + bitsPerInt - strlen(B), B, strlen(B));
/* compute A + B = C */
for (i = bitsPerInt - 1; i >= 0; --i) {
aBit = a[i] == '1'; bBit = b[i] == '1';
cBit = (aBit + bBit + carry) % 2;
carry = (aBit + bBit + carry) / 2;
C[i] = cBit + '0';
}
free(a);
free(b);
}
/* Return true if all characters of s are either '1' or '0'. */
bool isValidBinaryStr(const char *s) {
const char *p;
bool valid = true;
for (p = s; (*p != '\0') && (valid == true); p++) {
valid = ((*p == '1') || (*p == '0'));
}
return valid;
}
/* Get input string */
char *getStr(const char *prompt, char *str, size_t maxLen) {
char *p;
do {
printf("%s ",prompt);
if ((p = fgets(str, MAX_LINE_LEN, stdin)) != NULL) {
*(strchr(str,'\n')) = '\0';
}
} while ((strlen(str) == 0) || (strlen(str) > maxLen));
return p;
}
/* return pointer to first char != '0' in str */
const char *firstNonZero(const char *str) {
const char *p = str;
while ((*p != '\0') && (*p == '0')) ++p;
return p;
}
[/sourcecode]
I simply want to tell you that I am new to weblog and certainly savored this page. Almost certainly I’m want to bookmark your website . You amazingly come with perfect articles. Thanks a bunch for sharing with us your web site.
ReplyDelete