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

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

    This is a common homework problem. There's a cool loop that you can write that will compute the smallest power of 2 >= your target number n.

    Since it's a power of 2, the base 2 logarithm is the number of bits. But the Java math library only offers natural logarithm.

    math.log( n ) / math.log(2.0) 
    

    is the number of bits.

    0 讨论(0)
  • 2020-12-30 13:41
    import java.util.BitSet;
    
    public class StringifyByte {
    
        public static void main(String[] args) {
            byte myByte = (byte) 0x00;
            int length = 2;
            System.out.println("myByte: 0x" + String.valueOf(myByte));
            System.out.println("bitString: " + stringifyByte(myByte, length));
    
            myByte = (byte) 0x0a;
            length = 6;
            System.out.println("myByte: 0x" + String.valueOf(myByte));
            System.out.println("bitString: " + stringifyByte(myByte, length));
        }
    
        public static String stringifyByte(byte b, int len) {
            StringBuffer bitStr = new StringBuffer(len);
            BitSet bits = new BitSet(len);
            for (int i = 0; i < len; i++)
            {
               bits.set (i, (b & 1) == 1);
               if (bits.get(i)) bitStr.append("1"); else bitStr.append("0");
               b >>= 1;
            }
            return reverseIt(bitStr.toString());
        }
    
        public static String reverseIt(String source) {
            int i, len = source.length();
            StringBuffer dest = new StringBuffer(len);
    
            for (i = (len - 1); i >= 0; i--)
               dest.append(source.charAt(i));
            return dest.toString();
        }
    }
    

    Output:

    myByte: 0x0
    bitString: 00
    myByte: 0x10
    bitString: 001010
    
    0 讨论(0)
  • 2020-12-30 13:45

    Use Integer.toBinaryString() then check the string length and prepend it with as many zeros as you need to make your desired length.

    0 讨论(0)
  • 2020-12-30 13:45

    So here instead of 8 you can write your desired length and it will append zeros accordingly. If the length of your mentioned integer exceeds that of the number mentioned then it will not append any zeros

    String.format("%08d",1111);

    Output:00001111

    String.format("%02d",1111);
    

    output:1111

    0 讨论(0)
  • 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();
        }
    }
    
    0 讨论(0)
  • 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().

    0 讨论(0)
提交回复
热议问题