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

后端 未结 8 1216
有刺的猬
有刺的猬 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

    Forget about home-made solutions. Use standard BigInteger instead. You can specify number of bits and then use toString(int radix) method to recover what you need (I assume you need radix=2).

    EDIT: I would leave bit control to BigInteger. The object will internally resize its bit buffer to fit the new number dimension. Moreover arithmetic operations can be carried out by means of this object (you do not have to implement binary adders/multipliers etc.). Here is a basic example:

    package test;
    
    import java.math.BigInteger;
    
    public class TestBigInteger
    {
        public static void main(String[] args)
        {
            String value = "1010";
            BigInteger bi = new BigInteger(value,2);
            // Arithmetic operations
            System.out.println("Output: " + bi.toString(2));
            bi = bi.add(bi); // 10 + 10
            System.out.println("Output: " + bi.toString(2));
            bi = bi.multiply(bi); // 20 * 20
            System.out.println("Output: " + bi.toString(2));
    
            /*
             * Padded to the next event number of bits
             */
            System.out.println("Padded Output: " + pad(bi.toString(2), bi.bitLength() + bi.bitLength() % 2));
        }
    
        static String pad(String s, int numDigits)
        {
            StringBuffer sb = new StringBuffer(s);
            int numZeros = numDigits - s.length();
            while(numZeros-- > 0) { 
                sb.insert(0, "0");
            }
            return sb.toString();
        }
    }
    

提交回复
热议问题