连接两个数字的位的代码不起作用 [英] Code to concatenate two numbers' bits not working

查看:45
本文介绍了连接两个数字的位的代码不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务是连接两个给定数字的二进制。

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

示例:

给出 5 101 )和 3 011 ),结果为 46 concat(101,011)= 101011

Given 5 (101) and 3 (011), the result is 46 (concat(101, 011) = 101011)

到目前为止的代码:

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

}

但是问题在于代码给出 101110 ,而不是 101011

But the problem is that the above code gives 101110, not 101011.

什么是

推荐答案

您的问题是您正在向后 中输入第二个数字的位。这是因为 x%2 是低位:

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 尽我最大的艺术才能:-)但是,如果您已经知道它是3位宽,只需使用:

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.

这篇关于连接两个数字的位的代码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆