[ACCEPTED]-(Java) Specify number of bits (length) when converting binary number to string?-binary

Accepted answer
Score: 11

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

Score: 4

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

EDIT: I would leave bit control to BigInteger. The 6 object will internally resize its bit buffer 5 to fit the new number dimension. Moreover 4 arithmetic operations can be carried out 3 by means of this object (you do not have 2 to implement binary adders/multipliers etc.). Here 1 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();
    }
}
Score: 3

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

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

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

is 1 the number of bits.

Score: 1

Even simpler:

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

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

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

Score: 1

Try this:

String binaryString = String.format("%"+Integer.toString(size)+"s",Integer.toBinaryString(19)).replace(" ","0");

where size can be any number 1 the user wants

Score: 0
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

Score: 0

Here's a simple solution for int values; it 5 should be obvious how to extend it to e.g. byte, etc.

public static String bitString(int i, int len) {
    len = Math.min(32, Math.max(len, 1));
    char[] cs = new char[len];
    for (int j = len - 1, b = 1; 0 <= j; --j, b <<= 1) {
        cs[j] = ((i & b) == 0) ? '0' : '1';
    }
    return new String(cs);
}

Here 4 is the output from a set of sample test 3 cases:

  0   1                                0                                0
  0  -1                                0                                0
  0  40 00000000000000000000000000000000 00000000000000000000000000000000
 13   1                                1                                1
 13   2                               01                               01
 13   3                              101                              101
 13   4                             1101                             1101
 13   5                            01101                            01101
-13   1                                1                                1
-13   2                               11                               11
-13   3                              011                              011
-13   4                             0011                             0011
-13   5                            10011                            10011
-13  -1                                1                                1
-13  40 11111111111111111111111111110011 11111111111111111111111111110011

Of course, you're on your own to make 2 the length parameter adequate to represent 1 the entire value.

Score: 0

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

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

Output:00001111

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

output:1111

More Related questions