purani86
BAN USERpackage test;
import java.util.Stack;
public class BitWiseOperations {
static int bit(int num) {
StringBuffer sb = new StringBuffer();
Stack<Integer> stack = new Stack<Integer>();
while(num>=1) {
stack.push(num%2);
num = num/2;
}
while(!stack.isEmpty()) {
sb.append(stack.pop());
}
return Integer.valueOf(sb.toString());
}
static int bitAdd(int a, int b) {
Stack<Integer> stack = new Stack<Integer>();
int remainder = 0;
while (a>=1 || b>=1) {
int temp = (a%10)+(b%10)+remainder;
remainder=0;
if (temp <= 1) {
stack.push(temp);
} else {
stack.push(0);
remainder=1;
}
a=a/10;
b=b/10;
}
if (remainder == 1) {
stack.push(1);
}
StringBuffer sb = new StringBuffer();
while(!stack.isEmpty()) {
sb.append(stack.pop());
}
return Integer.valueOf(sb.toString());
}
static int convertBitToInt(int bitNum) {
int i=0;
int result = 0;
while(bitNum>=1) {
result += Math.pow(2, i)*(bitNum%10);
bitNum = bitNum/10;
i++;
}
return result;
}
public static void main(String[] args) {
int a = 4;
int b = 4;
int bitA = bit(a);
int bitB = bit(b);
System.out.println("Num A:: "+a);
System.out.println("Num B:: "+b);
System.out.println("Bit A:: "+bitA);
System.out.println("Bit B:: "+bitB);
int bitMulResult = bitA*bitB;
System.out.println("Bit Mul Result:: "+bitMulResult);
int bitAddResult = bitAdd(bitA, bitB);
System.out.println("Bit Add Result:: "+bitAddResult);
int mulResult = convertBitToInt(bitMulResult);
System.out.println("Int Mul Result:: "+mulResult);
int addResult = convertBitToInt(bitAddResult);
System.out.println("Int Result:: "+addResult);
}
}
- purani86 August 15, 2013