That will be a better option. Suppose I take two inputs as 100110. Now the I want to operate the 0th bit of i/p with the 1st bit. And this goes on upto the MSB. The operation can be anything like OR,AND, NOR, NAND, XOR and XNOR. For OR, the desired o/p is 10111. I think now you can understand.
Code -
#include <stdio.h>
#include <string.h>
int main()
{
char b[100],t;
int i,l=0;
scanf("%[^\t\n]s",b); /*scanf to accept multi-word string*/
for(i=0; b!='\0';i++)
{
b-='0';
l++;
}
for(i=0;i<l-1;i++)
{
t=b&b[i+1];
t=!t;
printf("\nNAND: %d", (t));
printf("\n");
}
return 0;
}
The program is working good in case of OR,AND and XOR. But its not giving the proper result while using NOT. If I use the bitwise ~ operator, the o/p is in 2's compliment form.
char i_number[32];
char o_number[32];
int length, a,b;
printf("Enter the binary number : ");
scanf("%s", i_number);
length = strlen(b_number);
// For AND operation;
for (int i = length-1 ; i>0; i++ )
{
if(i_number[i] == '0')
a = 0;
else
a =1;
if(i_number[i-1] == '0')
b = 0;
else
b = 1;
a = a&b;
o_number[i] = a;
}
if(i_number[0] == '0')
a = 0;
else
a =1;
if(i_number[length-1] == '0')
b = 0;
else
b = 1;
a = a&b;
o_number[i] = a;
a=!a;
o_number = a;
for (i=0;i<length;i++)
printf("%d",o_number);
return 0;
}
This is the complete code. Its working. But the complexity time is high in this case, and if we want to do all the operations, time will increase more.
Yeah the loop for printing the o/p is useless. But how to replace '!'? M trying too. I will let u know if I crack the code in an efficient manner.
@OP; create functions for all logical operations rather than embedding the conde in min itself.
for (i = length-1 ; i>0; i--)
{
if(i_number[i] == '0')
a = 0;
else
a =1;
if(i_number[i-1] == '0')
b = 0;
else
b = 1;