We help IT Professionals succeed at work.

# Binary using Char

on
Medium Priority
534 Views
I'm trying to find the best way to do binary addition and subtraction with Char's.

so say I've got:
char * a = '0001'
char * b = '0010'

I want it to return a char * that is the addition and subtraction of that number.

I've been simply converting it to decimal, and doing the math then converting back, but is there a better way?
Comment
Watch Question

## View Solutions Only

Data Warehouse / Database Architect
CERTIFIED EXPERT

Commented:
Hi cfans,

What you're doing is fine, as long as the value(s) will all fit in one of the native integer types (char, int, long, long long).

If you expect data that is larger than the system can handle, you'll have to walk through the strings yourself adding the bits and keeping track of the carries.

Good Luck!
Kent
Commented:
If I assume a & b to be always positive.

you can use a flow like:

// keep adding till one of your input attay is out of chars
remainder = get remainder that u get when you add a, b and prevRemainder

sum[count] = convert a, b and remainder to int. add a, b and remainder. convert to ascii.

prevRemainder = remainder

// atleast one of the inputs has hit its end of array.
// keep copying the other input's chars one by one. Don't forget the remainder!

sum[count] =  convert (a or b) and remainder to int. add them. convert to ascii.

be cautious with ascii to int, int to ascii conversions. a '1' is not same as value 1.

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
What is the length of your input ? How would you represent negative numbers ?

an addition algorithm is very simple in one pass over the data.
Commented:
if you'll use Vikram_B proposal, I would use a simple tabe

a b Reminder  -> Sum Reminder
0 0 0                  0      0
0 0 1                  1      0
0 1 0                  1      0
0 1 1                  0      1
1 0 0                  1      0
1 0 1                  0      1
1 1 0                  0      1
1 1 1                  1      1

or a few bit operations to have the same results...

Commented:
Currently u are doing decimel addisions and subtractions.That is better way i can find some other ways but it is not faster.

i doing like this just accept the binary type data as input and use one binary to decimal converter and manipulate. then convert back using decimel to binary converter function
Access more of Experts Exchange with a free account
##### Thanks for using Experts Exchange.

Limited access with a free account allows you to:

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile