The task is to concat the binary of 2 given numbers.
Example:
Given 5
(101
) and 3
(011
),
Your problem is that you're feeding the bits of the second number in backwards. That's because x%2
is the low order bit:
+---+---+---+ <110
| 1 | 0 | 1 | <-----------------+^
+---+---+---+ |1
+---+---+---+ |1
| 0 | 1 | 1 | ----+0
+---+---+---+ 011>
Cringe at my awesome artistic abilities :-) However, if you already know that it's 3 bits wide, just use:
public class concat {
public static void main (String[] args) {
int t = 0;
int k = 5;
int x = 3;
k <<= 3;
k |= x;
// or, in one line: k = (k << 3) | x;
System.out.println(k);
}
}
In terms of how that looks graphically:
+---+---+---+
k:| 1 | 0 | 1 |
+---+---+---+
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
+---+---+---+---+---+---+
k<<=3:| 1 | 0 | 1 | 0 | 0 | 0 |
+---+---+---+---+---+---+
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
+---+---+---+---+---+---+
k|=3:| 1 | 0 | 1 | 0 | 1 | 1 |
+---+---+---+---+---+---+
^ ^ ^
+---+---+---+
x:| 0 | 1 | 1 |
+---+---+---+
There's no apparent reason for doing it one bit at a time.
You just shift
one number and then or
with the other number:
int a = 5;
int b = 3;
int c = (a << 3) | b;
I don't know what language you are using, it's almost Java, so I am going with that.
This returns the result you are asking for, though you haven't given rules for determining how you know that 3 should be 011 instead of 11.
I have made the assumption that you want to assume that both numbers have the same number of bits, so 3 is 011 because 5 requires 3 bits.
public class Concat {
public static void main(String[] args) {
System.out.println( joinNums(3,5) );
}
public static int numBits( int n ) {
return (int)Math.ceil( Math.log(n) / Math.log(2) );
}
public static int joinNums( int num1 , int num2 ) {
int bits = Math.max( numBits(num1) , numBits(num2) );
return (num1 << bits) + num2;
}
}