1

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 , ' ');
dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Atomix
  • 125
  • 1
  • 2
  • 9
  • What has your teacher told you to use? – Thorbjørn Ravn Andersen Jan 31 '21 at 07:47
  • Actually nothing special... But i think that the simpler the better. I've tried to use string builder but maybe that's not the best solution, however if you could do that using StringBuilder it also would be ok. – Atomix Jan 31 '21 at 07:51
  • It seems you may need to clarify with your instructor if your approach is ok. Maybe the task implies using `byte` type and bitwise `&` ,`|` and shift `<<` operations. – Nowhere Man Jan 31 '21 at 08:15
  • Try searching for bitwise operators and how to use them in java. For example one way to reset LSB can be ```int number = 0b00001011;``` and then doing a bitwise XOR ```number = number ^ 1; ``` – Wasim Zarin Jan 31 '21 at 08:23

1 Answers1

2

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

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
Dmitrii B
  • 2,672
  • 3
  • 5
  • 14