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

问题描述 投票:0回答:1

我想做一个程序,用位运算符打印用户给定的int的第一个和最后一个二进制值。例如,如果用户输入5,输出应该是 "二进制值是0101。MSB是0,LSB是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 binary bitwise-operators
1个回答
2
投票

在Java中,整数是32位(-1位为+-)。

    int i = 1073741824;

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

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

请注意,任何小于1073741824的数字将返回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)
© www.soinside.com 2019 - 2024. All rights reserved.