打印用户输入的 int 的 MSB 和 LSB

Print the MSB and LSB of a user entered int

我正在尝试制作一个程序,该程序将使用按位运算符打印给定 int 的用户的第一个和最后一个二进制值。例如,如果用户输入 5,则输出应为 "Binary Value is 0101. MSB is 0, LSB is 1." 到目前为止,这是我所拥有的,它似乎有效,但我觉得它是错误的。此外,JAVA 似乎没有在较小的数字前面添加 0。例如,5 的输出不是 0101,而是 101,这改变了(至少对用户而言)MSB 和 LSB 是什么。 任何帮助将不胜感激,我是按位的新手,所以如果你能保持相对简单,那就太好了。


public class LSBAndMSB {
    public static void main (String [] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Hello! Please enter an integer.");
        int in = sc.nextInt();

        int first = 2;
        int MSB = MSB(in, first);
        int LSB = LSB(in, first);
        String binary = binary(in);

        System.out.print("You entered: " + in + ". The binary of this"
                + " number is: " + binary
                + ".\nThe MSB of the int " + in + " is: " + MSB +
                ".\nThe LSB of the int " + in + " is: " + LSB);


    }

    public static String binary(int out) {
        return Integer.toBinaryString(out);
    }

    public static int LSB (int out, int pos) {
            out = (out & (1 << (pos - 2)));
            return out;
    }

    public static int MSB (int out, int pos) {
        if (out > 0) {
            out = (~ out & out);
            return out;
        } else {
            out = (~ out & 0);
            return out;
        }
    }
}

Java 中的整数是 32 位(+/- 为 -1 位)

    int i = 1073741824;

    int MSB = i >>> 30;
    int LSB = i & 1;

    System.out.println("MSB: " + MSB + " LSB: " + LSB);

请注意,任何小于 1073741824 的数字都将 return 0 作为 MSB

如果您想要其他尺码:

8 bit  -> i >>> 7
16 bit -> i >>> 15
24 bit -> i >>> 23
32 bit -> i >>> 30 (this is actually 31 bit, max size for Integers in Java)