1

Is there a better way to get bit[] from binary string
e.g.
Let say I want bits from index=3 up to length (len=5)
BinaryString = 10011000000000010000111110000001
Expected Result = 11000

This is what I have so far.

Method 1

    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);
}

Method 2

    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);
}
Ben Isaac
  • 69
  • 1
  • 10

1 Answers1

0

i think value.substring(int,int) do fine.

Charif DZ
  • 14,415
  • 3
  • 21
  • 40