The task is to concat the binary of 2 given numbers.
Example:
Given 5 (101) and 3 (011), the result is 46 (concat(101, 011) = 101011)
The code thus far:
public class Concat {
public static void main(String[] args) {
int t = 0;
int k = 5;
int x = 3;
int i = 0;
while (i < 3) {
t = x % 2;
x /= 2;
k <<= 1;
k |= t;
++i;
}
System.out.println(k);
}
}
But the problem is that the above code gives 101110, not 101011.
What’s the problem?
Your problem is that you’re feeding the bits of the second number in backwards. That’s because
x%2is the low order bit:Cringe at my awesome artistic abilities 🙂 However, if you already know that it’s 3 bits wide, just use:
In terms of how that looks graphically:
There’s no apparent reason for doing it one bit at a time.