(Java)在将二进制数转换为字符串时指定位数(长度)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/625838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(Java) Specify number of bits (length) when converting binary number to string?
提问by joinJpegs
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 need a string "00". Or 1010 with 6 bits so "001010".
例如,如果我需要用两位存储 0,我需要一个字符串“00”。或者 1010 有 6 位所以“001010”。
Can anyone help?
任何人都可以帮忙吗?
EDIT: Thanks guys, as I'm rubbish at maths/programming in general I've gone with the simplest solution which was David's. Something like:
编辑:谢谢大家,因为我在数学/编程方面一般都是垃圾,所以我采用了最简单的解决方案,即大卫的解决方案。就像是:
binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
binaryString.insert(0, "0");
}
It seems to work fine, so unless it's very inefficient I'll go with it.
它似乎工作正常,所以除非它非常低效,否则我会继续使用它。
采纳答案by David Z
Use Integer.toBinaryString()
then check the string length and prepend it with as many zeros as you need to make your desired length.
使用Integer.toBinaryString()
然后检查字符串长度并在它前面加上尽可能多的零以达到所需的长度。
回答by Fernando Miguélez
Forget about home-made solutions. Use standard BigIntegerinstead. You can specify number of bits and then use toString(int radix) method to recover what you need (I assume you need radix=2).
忘记自制的解决方案。请改用标准BigInteger。您可以指定位数,然后使用 toString(int radix) 方法来恢复您需要的内容(我假设您需要 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:
编辑:我会将位控制留给 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();
}
}
回答by S.Lott
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.
这是一个常见的家庭作业问题。您可以编写一个很酷的循环来计算 2 >= 目标数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.
由于它是 2 的幂,因此以 2 为底的对数是位数。但是 Javamath
库只提供自然对数。
math.log( n ) / math.log(2.0)
is the number of bits.
是位数。
回答by Alex Reynolds
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
回答by joel.neely
Here's a simple solution for int
values; it should be obvious how to extend it to e.g. byte, etc.
这是一个简单的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);
}
Here is the output from a set of sample test 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 the length parameter adequate to represent the entire value.
当然,您需要自己使长度参数足以表示整个值。
回答by jkschneider
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().
这里的想法是暂时将字符串解析为十进制数(恰好包含所有 1 和 0 的十进制数),然后使用 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()
.
请注意,您基本上必须使用 BigInteger,因为如果您尝试使用Integer.fromString()
或,二进制字符串会迅速溢出 Integer 和 Long 导致 NumberFormatExceptions Long.fromString()
。
回答by Anshuman Anjani Kumar
Try this:
尝试这个:
String binaryString = String.format("%"+Integer.toString(size)+"s",Integer.toBinaryString(19)).replace(" ","0");
where size can be any number the user wants
其中 size 可以是用户想要的任何数字
回答by agarr3290417
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
所以在这里你可以写你想要的长度而不是 8,它会相应地附加零。如果您提到的整数的长度超过提到的数字的长度,则不会附加任何零
String.format("%08d",1111);
String.format("%08d",1111);
Output:00001111
输出:00001111
String.format("%02d",1111);
output:1111
输出:1111