Search code examples
javabinarybitwise-operators

Print the MSB and LSB of a user entered int


Im trying to make a program that will print the first and last binary value of a user given int using bitwise operators. For example, if a user inputs 5, the output should be "Binary Value is 0101. MSB is 0, LSB is 1." This is what I have so far, and it seems to work but i feel like its wrong. Also, JAVA doesnt seem to add the 0's in front of smaller numbers. For example, the output of 5 is not 0101, but instead 101, which changes (at least to the user) what the MSB and LSB are. Any help would be greatly appreciated, and im new to bitwise, so if you could keep it relatively simple that would be great.


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

Solution

  • Integers in Java are 32 bit (-1 bit for +/-)

        int i = 1073741824;
    
        int MSB = i >>> 30;
        int LSB = i & 1;
    
        System.out.println("MSB: " + MSB + " LSB: " + LSB);
    

    Please be aware that any number smaller than 1073741824 will return 0 as MSB

    If you want othe sizes:

    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)