tags:

views:

59

answers:

3

i want following suppose there is given two number 5 and 3 for example
5//101 and 3 //011 to concat these bits 101110 and we get 46 here is code for this task

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);
    }

}

i have question how can done vice verse or not 101110 but 101011? thanks

+1  A: 

You just shift one number and then or with the other number:

int a = 5;
int b = 3;
int c = (a << 3) | b;
Guffa
not not correct are u sure that it is correct?
sorry one minute
yes correct i have made one mistake
thanks Guffa thanks very much
+2  A: 

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.

paxdiablo
A: 

Hi, 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;
  }
}
Joshua Cheek