Code to concatenate two numbers' bits not working

后端 未结 3 1003
自闭症患者
自闭症患者 2021-01-14 14:16

The task is to concat the binary of 2 given numbers.

Example:

Given 5 (101) and 3 (011),

相关标签:
3条回答
  • 2021-01-14 14:42

    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.

    0 讨论(0)
  • 2021-01-14 14:53

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

    int a = 5;
    int b = 3;
    int c = (a << 3) | b;
    
    0 讨论(0)
  • 2021-01-14 14:57

    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;
      }
    }
    
    0 讨论(0)
提交回复
热议问题