问题描述
创建一个值为 00001011 的 8 位变量。重置 LSB 位。放 MSB 位。设置第 2 位。检查是否设置了第 4、5、6 位。做一个 位号 3 取反,显示数据并再次取反。移动 向左两位整数
到目前为止,我做了这样的事情,但我卡住了:
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,' ');
解决方法
您可以使用 BitSet
进行最需要的操作,例如:
//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,6 are set");
}
//Make a bit number 3 inversion
if (source.get(3)){
source.clear(3);
}else {
source.set(3);
}
System.out.println(source);
在java-bitset中查看更多