Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 518
  • Last Modified:

Binary using Char

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?
0
cfans
Asked:
cfans
2 Solutions
 
Kent OlsenData Warehouse Architect / DBACommented:
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
0
 
Vikram_BCommented:
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.

0
 
zultiCommented:
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.
0
 
zultiCommented:
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...
 
0
 
deepu chandranCommented:
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
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now