Another C Question

Programming, for all ages and all languages.
Post Reply
The_Human

Another C Question

Post by The_Human »

I just wanted to know, is it possible to add two numbers without using any arithmatic operator?
Schol-R-LEA

Re:Another C Question

Post by Schol-R-LEA »

I suppose so, using the appropriate bitwise operators. Pardon me if I'm too short on time to give the full details.
ark

Re:Another C Question

Post by ark »

since at the very, very lowest levels all you've got are and, or and not operations and things like that, the answer is yes. You can implement addition without explicitly using the "+" operator. I don't remember off the top of my head how it's done but it isn't something I'd recommend unless you actually need to do so (and I can't imagine any reason short of hardware emulation why you'd need to). I had it as an exercise in a computer architecture course in college.
Curufir

Re:Another C Question

Post by Curufir »

Kinda pointless since the nice processor manufacturer's have provided the circuitry for it, but I guess that's no reason to be curious.

Full-adder circuit boolean looks kinda like:

S[sub]i[/sub] = (X[sub]i[/sub] XOR Y[sub]i[/sub]) XOR C[sub]i[/sub]

C[sub]o[/sub] = (X[sub]i[/sub] XOR Y[sub]i[/sub])C[sub]i[/sub] + XY

That gives you sum and carry calculated from two input bits X[sub]i[/sub] and Y[sub]i[/sub] and the previous carry C[sub]i[/sub].

[pre]
Truth table

X Y C | C[sub]o[/sub] S
------|-----
0 0 0 | 0 0
0 0 1 | 0 1
0 1 0 | 0 1
0 1 1 | 1 0
1 0 0 | 0 1
1 0 1 | 1 0
1 1 0 | 1 0
1 1 1 | 1 1
[/pre]
Rinse and repeat for the number of bits you have in your binary number to produce the sum of two numbers.

This isn't the optimal set of equasions if you know the size of the binary numbers in advance and it'll be WAY less efficient than having the processor just do an add. If you have a specific number of bits in mind then matlab, a few hours, and an understanding of circuit reduction will give you something better. Either that or ask your nearest EE professor.
Post Reply