I need to write 4 C functions, whhich emulate the C operators |, ^, ~, and !=. I am not sure what what I am doing wrong. I can not use loops or conditionals. Below is my code.
#include <stdio.h>
int main( )
{
int a = 1, b =2;
int bitOr(a, b)
{ int Or;
Or = a | b;
}
int bitXOr(a, b)
{int XOr;
XOr = a^b;
}
int bitNot(a)
{int Not;
Not = ~a;
}
int isNotEqual(a,b)
{int NEq;
NEq = a!=b;}
}
1. Some compilers assume a parameter with no type is int. This is not standard.
2. When you give a function a return type, every possible control path must have one return statement.
I'll fix your bitOr() as an example. You do the rest.
Thank you for your help helios. I was not sure about the int a and int b. I just found that I can not use the | for bitOr , ^ for bitXOr etc. so how would I write the function?
Say you have two number you want to perform bitwise OR on (I'll use bytes because it's too tedious):
11000010
01111011
x&1 will give you the LSB (least significant bit) of any number, and x>>=1 will shift all the bits one place to the right (it's the same as doing x/=2). So what you do is remove each bit and perform the operation sizeof(type)*8 times.
To perform the actual operation, use a simple if. Before entering the if, right shift the result value (which should be initialized to zero). For the true case, add 1<<(sizeof(type)*8-1) to the result value. The false case should do nothing.
Example:
Step 0:
11000010(a)&1==0
01111011(b)&1==1
11000010(a)>>=1 -> 01100001
01111011(b)>>=1 -> 00111101
00000000(r)>>=1 -> 00000000
0||1==1 therefore 00000000(r)+=(1<<(sizeof(byte)*8==8)==128) -> 10000000
Step 1:
01100001(a)&1==1
00111101(b)&1==1
01100001(a)>>=1 -> 00110000
00111101(b)>>=1 -> 00011110
10000000(r)>>=1 -> 01000000
1||1==1 therefore 01000000(r)+=128 -> 11000000
Step 2:
00110000(a)&1==0
00011110(b)&1==0
00110000(a)>>=1 -> 00011000
00011110(b)>>=1 -> 00001111
11000000(r)>>=1 -> 01100000
0||0==1 therefore