This question already has answers here:
Add two integers using only bitwise operators?
(8 answers)
How to add two numbers without using ++ or + or another arithmetic operator
(21 answers)
Closed 6 years ago.
I was asked this question in an interview:
How to add two variables without using a '+' operator?
The interviewer asked me and I could not answer, even though I am a good C programmer!
Using bitwise operators you can add two numbers. Try below:
int Sum(int a, int b)
{
// Iterate till there is no carry
while (b != 0)
{
// now carry contains common set bits of a and b
int carry = a & b;
// Sum of bits of a and b where at least one of the bits is not set
a = a ^ b;
// Carry is shifted by one so that adding it to a gives the required sum
b = carry << 1;
}
return a;
}
Using Increment and decrement operators you can add two numbers.
The other way may be like:
int Sum(int a, int b)
{
// Iterate till there b becomes zero
while (b--)
{
a++;
}
return a;
}
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Why are floating point numbers inaccurate?
(5 answers)
Is floating-point == ever OK?
(14 answers)
Closed 11 months ago.
sample code is here, desire output is 2 ::
#include <stdio.h>
int main()
{
double i, a, b;
int j;
for (i = 0; i <= 3; i = i + .20)
{
if (i == 2)
{
printf("I=%lf\n", i);
}
}
}
When I use
#include <stdio.h>
int main()
{
double i, a, b;
int j;
for (i = 0; i <= 3; i = i + .25)
{
if (i == 2)
{
printf("I=%lf\n", i);
}
}
}
it works; but in the first case, it is not working. WHY ??
The short answer is that the use of a floating control variable for a for loop is unwise... comparing a floating value for equality is even less so.
Due to the storage of floating point numbers as a mantissa and an exponent, your 0.20000000 may well be 0.199999999...9 or 020000000...01 thus the comparison fails.
Typically, 0.25 and 2.000 will store exactly, as they are powers of 2. Hence a step of 0.25 works as anticipated.
MISRA C:2012 has Rule 14.1 to protect against using float or doubles as loop counters... and previously had a Rule to protect against testing float/double for equality -perhaps we should reinstate that Rule.
This question already has answers here:
How to concatenate two integers in C
(10 answers)
Closed 5 years ago.
Currently I am having a speed bump with adding two different integers. For example
int i = 32;
int j = 50;
/* Add i and j together into 3250 */
What I thought was changing the integers into strings and add them together but that takes too much effort. Is there any other way?
The solution in the decimal system is:
int result = 100* i + j;
In case this should be generic you'll need the following algorithm:
int shift = 10;
while(j >= shift) {
pow *= 10;
}
int result = i * pow + j;
This question already has answers here:
Catch and compute overflow during multiplication of two large integers
(14 answers)
Closed 9 years ago.
int isOverflow(uint a, uint b) {
// a and b are unsigned non-zero integers.
uint c = a * b;
if (c < ( a > b ? a : b))
return 1;
else
return 0;
}
Am I missing something ? I think the above snippet will work.
EDIT : I have seen other solutions like multiplication of large numbers, how to catch overflow which uses some fancy methods to check it. But to me above simple solution also looks correct. Thats why I am asking this question.
It's easy to prove this is wrong by finding an exception:
Consider these two 8-bit unsigned values: a = 0x1F and b = 0xF.
c = a * b
c = 0x1F * 0xF
c = 0xD1 (Overflow! The real answer is 0x1D1)
c < ( a > b ? a : b)
0xD1 < 0x1F => False (Wrong!)
A correct answer is here.
CERT has a great document INT30-C. Ensure that unsigned integer operations do not wrap which covers all the cases of unsigned integer overflow and check they advocate for multiplications requires that you test before you perform the multiplication to prevent the overflow before it occurs (I modified the example to fit your questions):
if (a > SIZE_MAX / b) {
/* Handle error condition */
}
c = a * b;
This is a straight forward solution to your problem, it has been solved and you should use the solutions that have been proven to work, coming up with your own solutions can be error prone.
This question already has answers here:
How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers
(16 answers)
Closed 9 years ago.
Ok So I know and understand the difference between MOD and REM. I also am aware that C's % operation is a REM operation. I wanted to know, and could not find online, if there is some C library or function for an explicit MOD.
Specifically, I'd like (-1)%4 == 3 to be true. In C (-1)%4 = -1 since it is a remainder. And preferably I'd like to avoid using absolute values and even better would be to utilize some built in function that I can't seem to find.
Any advice will be much appreciated!
The best option I can think of is to compute:
((-1 % 4) + 4 ) % 4
Here you may replace -1 with any value and you will get MOD not REM.
The most common way to do what you expect is:
((a % b) + b ) % b
It works because (a % b) is a number in ]-b; b[ so (a % b) + b is positive (in ]0; 2 * b[) and adding b did not changed the mod.
Just do,
int mod(int a, int b)
{
int res = a % b;
return(res < 0 ? (res + b) : res);
}
Every negative res content after MOD operation is added to b to get modulus of a & b.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I multiply and divide using only bit shifting and adding?
I have to write functions to perform binary subtraction, multiplication, and division without using any arithmetic operators except for loop control. I've only written code in Java before now, so I'm having a hard time wrapping my head around this.
Starting with subtraction, I need to write a function with prototype
int bsub(int x, int y)
I know I need to convert y to two's complement in order to make it negative and add it to x, but I only know how to do this by using one's complement ~ operator and adding 1, but I can't use the + operator.
The badd function was provided, and I will be able to implement it in bsub if I can figure out how to make y a negative number. The code for badd is shown below. Thanks in advance for any tips.
int badd(int x,int y){
int i;
char sum;
char car_in=0;
char car_out;
char a,b;
unsigned int mask=0x00000001;
int result=0;
for(i=0;i<32;i++){
a=(x&mask)!=0;
b=(y&mask)!=0;
car_out=car_in & (a|b) |a&b;
sum=a^b^car_in;
if(sum) {
result|=mask;
}
if(i!=31) {
car_in=car_out;
} else {
if(car_in!=car_out) {
printf("Overflow occurred\n");
}
}
mask<<=1;
}
return result;
}
Well, subtracting in bitwise operations without the + or - operators is slightly tricky, but can be done. You have the basic idea with the complement, but without using + it becomes slightly tricky.
You can do it by first setting up addition with bit-wise only, then using that, you can do subtraction. Which is used for the complement, So the code looks like this:
int badd(int n1, int n2){
int carry, sum;
carry = (n1 & n2) << 1; // Find bits that are used for carry
sum = n1 ^ n2; // Add each bit, discard carry.
if (sum & carry) // If bits match, add current sum and carry.
return badd(sum, carry);
else
return sum ^ carry; // Return the sum.
}
int bsub(int n1, int n2){
// Add two's complement and return.
return badd(n1, badd(~n2, 1));
}
And then if we use the above code in an example:
int main(){
printf("%d\n", bsub(53, 17));
return 0;
}
Which ends up returning 36. And that is how subtraction works with bitwise only operations.
Afterwards multiplication and division get more complicated, but can be done; for those two operations, use shifts along with addition and/or subtraction to get the job done. You may also want to read this question and this article on how to do it.
You have to implement the binary addition first:
Example with 4 bits:
a = 1101
b = 1011
mask will range from 0001 to 1000
for (i=0;i<4;i++) {
x = a & pow(2, i); //mask, you can shift left as well
y = b & pow(2, i);
z = x ^ y; //XOR to calculate addition
z = z ^ carry; //add previous carry
carry = x & y | x ^ carry | y ^ carry; //new carry
}
This is pseudocode. The mask allows for operating bit by bit from left to right. You'll have to store z conveniently into another variable.
Once you have the addition, you'll be able to implement subtraction by 1'complementing and adding 1.
Multiplication goes the same way, but slightly more difficult. Basically it's the same division method you learned at school, using masks to select bits conveniently and adding the intermediate results using the addition above.
Division is a bit more complicated, it would take some more time to explain but basically it's the same principle.