从二进制字符串中获取 n 位
Get n bits from binary string
有没有更好的方法从二进制字符串中获取位[]
例如
假设我想要从 index=3 到长度 (len=5)
BinaryString = 10011000000000010000111110000001
预期结果 = 11000
这是我目前所拥有的。
方法一
public void getBits1(){
int idx = 3;
int len = 5;
String binary = new BigInteger("98010F81", 16).toString(2);
char[] bits = binary.toCharArray();
String result = "";
//check here: to make sure len is not out of bounds
if(len + idx > binary.length())
return; //error
for(int i=0; i<len; i++){
result = result + bits[idx];
idx++;
}
//original
System.out.println(binary);
//result
System.out.println(result);
}
方法二
public void getBits2(){
int idx = 3;
int len = 5;
String binary = new BigInteger("98010F81", 16).toString(2);
String result = binary.substring(idx, len+idx);
//original
System.out.println(binary);
//result
System.out.println(result);
}
我认为 value.substring(int,int) 做的很好。
有没有更好的方法从二进制字符串中获取位[]
例如
假设我想要从 index=3 到长度 (len=5)
BinaryString = 10011000000000010000111110000001
预期结果 = 11000
这是我目前所拥有的。
方法一
public void getBits1(){
int idx = 3;
int len = 5;
String binary = new BigInteger("98010F81", 16).toString(2);
char[] bits = binary.toCharArray();
String result = "";
//check here: to make sure len is not out of bounds
if(len + idx > binary.length())
return; //error
for(int i=0; i<len; i++){
result = result + bits[idx];
idx++;
}
//original
System.out.println(binary);
//result
System.out.println(result);
}
方法二
public void getBits2(){
int idx = 3;
int len = 5;
String binary = new BigInteger("98010F81", 16).toString(2);
String result = binary.substring(idx, len+idx);
//original
System.out.println(binary);
//result
System.out.println(result);
}
我认为 value.substring(int,int) 做的很好。