【问题标题】:Get n bits from binary string从二进制字符串中获取 n 位
【发布时间】:2016-07-13 03:24:16
【问题描述】:

有没有更好的方法从二进制字符串中获取 bit[]
例如
假设我想要从 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);
}

【问题讨论】:

  • 方法 2 对我来说很好

标签: java binary bit-shift bits


【解决方案1】:

我认为 value.substring(int,int) 很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多