(Java)指定将二进制数转换为字符串时的位数(长度)?

StackOverflow https://stackoverflow.com/questions/625838

  •  05-07-2019
  •  | 
  •  

我正在尝试将数字存储为数组中的二进制字符串,但我需要指定将其存储为多少位。

例如,如果我需要用两位存储0,我需要一个字符串“00”。或者1010具有6比特,因此“001010”。

有人可以帮忙吗?

编辑:谢谢你们,因为我对数学/编程总体上很垃圾,所以我选择了大卫的最简单的解决方案。类似的东西:

binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
                        binaryString.insert(0, "0");
}

它似乎工作正常,所以除非效率非常低,否则我会继续使用它。

有帮助吗?

解决方案

使用 Integer.toBinaryString()然后检查字符串长度,并在其前面添加尽可能多的零,以达到所需的长度。

其他提示

忘记自制解决方案。请改用标准 BigInteger 。你可以指定位数,然后使用toString(int radix)方法来恢复你需要的东西(我假设你需要radix = 2)。

编辑:我会将位控制留给BigInteger。该对象将在内部调整其位缓冲区的大小以适应新的数字维度。此外,算术运算可以通过这个对象来执行(你不必实现二进制加法器/乘法器等)。这是一个基本的例子:

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();
    }
}

这是一个常见的家庭作业问题。你可以编写一个很酷的循环来计算2> =你的目标数 n 的最小功率。

由于它是2的幂,因此基数2的对数是位数。但Java math 库只提供自然对数。

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

是位数。

更简单:

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

这里的想法是暂时将字符串解析为十进制数(一个恰好包含所有1和0),然后使用String.format()。

请注意,您基本上必须使用BigInteger,因为如果您尝试使用 Integer.fromString() Long.fromString()<,二进制字符串会快速溢出Integer和Long,从而导致NumberFormatExceptions /代码>

试试这个:

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

其中size可以是用户想要的任何数字

这是 int 值的简单解决方案;应该明白如何将其扩展到例如字节等。

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);
}

以下是一组示例测试用例的输出:

  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

当然,你可以自己使长度参数足以代表整个值。

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();
    }
}

输出:

myByte: 0x0
bitString: 00
myByte: 0x10
bitString: 001010

所以在这里而不是8你可以写出你想要的长度,它会相应地附加零。如果您提到的整数的长度超过了上述数字的长度,那么它将不会附加任何零

<代码>的String.format(QUOT;%08D&QUOT;,1111);

  

输出:00001111

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

输出:1111

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top