(Java) Specify number of bits (length) when converting binary number to string?

后端 未结 8 1203
有刺的猬
有刺的猬 2020-12-30 13:03

I\'m trying to store a number as a binary string in an array but I need to specify how many bits to store it as.

For example, if I need to store 0 with two bits I ne

8条回答
  •  借酒劲吻你
    2020-12-30 13:47

    Even simpler:

    String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));  
    String.format("%032", new BigInteger(binAddr)); 
    

    The idea here is to parse the string back in as a decimal number temporarily (one that just so happens to consist of all 1's and 0's) and then use String.format().

    Note that you basically have to use BigInteger, because binary strings quickly overflow Integer and Long resulting in NumberFormatExceptions if you try to use Integer.fromString() or Long.fromString().

提交回复
热议问题