It is necessary to replace one bit (from 0 to 1 and vice versa) with a choice in a fixed 8-bit number:

10011010

A number is selected from 1 to 8. For example, selecting 5 displays 10010010 (5 bits changed from 1 to 0)

In addition, you need to create a string to display the number (int) in 8-bit format:

String.format("%8s", Integer.toBinaryString(meinInteger)).replace(' ', '0'); 
  • 2
    And with what problems you have when solving a problem yourself? - Regent
  • I don’t even know where to start. To set the whole number or separately? - Zhenya
  • And where to use this line to output numbers in the 8-bit format - Zhenya
  • And another question, how to choose a separate bit in the number? using the scanner to set the number from 1 to 8? - Zhenya
  • "whole or separate" - what do you mean by this? From where and in what form (just byte, or int number 10011010, or the string "10011010") does the value come to you? - Regent

1 answer 1

  1. Get the position 1-8 ( place ). Where does it come from and whether it should be checked for validity of the value is beyond the scope of the question. The example just reads the number from the console.
  2. Write the original number ( number ). For convenience, you can specify a binary literal . Whether to store it as int or byte is not important in this case.
  3. Invert (0 -> 1, 1 -> 0) the desired bit. To do this, you can use the xor- th with the appropriate degree of two. The power of two can be obtained from a unit of one bitwise left shift for the required number of positions. Numbers of bits are counted from right to left, starting from zero, therefore the shift is not made on place or place - 1 , but on 8 - place
  4. We get the resulting string using the construction in question

Example final code:

 Scanner scanner = new Scanner(System.in); int place = scanner.nextInt(); int number = 0b10011010; number ^= 1 << (8 - place); String result = String.format("%8s", Integer.toBinaryString(number)).replace(' ', '0'); System.out.println(result); 

When you enter 5 output:

10010010