(Java)指定将二进制数转换为字符串时的位数(长度)? [英] (Java) Specify number of bits (length) when converting binary number to string?
问题描述
我正在尝试将数字存储为数组中的二进制字符串,但我需要指定将其存储为多少位。
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.
例如,如果我需要用两位存储0我需要一个字符串00。或者1010有6位所以001010。
For example, if I need to store 0 with two bits I need a string "00". Or 1010 with 6 bits so "001010".
任何人都可以帮忙吗?
编辑:谢谢大家,我对数学/编程总体上很垃圾我已经选择了大卫的最简单的解决方案。类似于:
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.
推荐答案
使用 Integer.toBinaryString()
然后检查字符串长度并在它前面加上你想要的长度所需的零。
Use Integer.toBinaryString()
then check the string length and prepend it with as many zeros as you need to make your desired length.
这篇关于(Java)指定将二进制数转换为字符串时的位数(长度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!