Atomix
Atomix

Reputation: 125

MSB and LSB in java

I have an exercise in java, here it is:

Create an 8 bit variable with value of 00001011. Reset an LSB bit. Set MSB bit. Set bit number 2. Check if bit number 4, 5, 6 are set. Make a bit number 3 inversion, display data and invert it again. Move the whole number two bits to the left

So far, I made something like this, but I'm stuck:

package com.company;

public class Main {

    public static void main(String[] args) {
    // write your code here

        StringBuilder bajt =new StringBuilder("00001011");
        bajt.setCharAt(7 , '0');
        int bajt_1 = Integer.parseInt(bajt.toString(),2);
        String bajt_bin = Integer.toBinaryString(bajt_1);
        System.out.println("postac decymalna po pierwszej operacji:" +  bajt_1);
        System.out.println("postac binarna po pierwszej operacji:" +  bajt_bin);
        bajt.setCharAt(0 , ' ');

Upvotes: 1

Views: 750

Answers (1)

Dmitrii B
Dmitrii B

Reputation: 2860

You can use BitSet for most needed manipulation, for example:

     //initialization
    BitSet source = new BitSet(8);
    source.set(5);
    source.set(7);
    source.set(8);
    //MSB bit position
    int msbBit = source.nextSetBit(1);
    //LSB bit position
    int lsbBit = source.previousSetBit(8);
    //Reset an LSB bit
    source.clear(lsbBit);
    //Set bit number 2.
    source.set(2);
    //Check if bit number 4,5,6 are set
    if (source.get(4) && source.get(5) && source.get(6)){
        System.out.println("Bit 4, 5, 6 are set");
    }
    //Make a bit number 3 inversion
    if (source.get(3)){
        source.clear(3);
    }else {
        source.set(3);
    }
    System.out.println(source);

see more in java-bitset

Upvotes: 2

Related Questions