这就是我要做的,我有一个小数位串,像这样: String s="55795556555.....", 我想把它转换成字节数组:
String s="55795556555.....",
byte[] array=s.getbyte(),
然后将该字节数组传递给biginteger:
BigInteger number=new BigInteger(array),
然后将其转换为二进制字符串:
String str=number.toString(2),
我搞错了二进制表示法。。。为什么?如何修复?
9rygscc11#
按以下步骤操作:
import java.math.BigInteger;public class Main { public static void main(String[] args) { String s = "55795556555123"; BigInteger number = new BigInteger(s); System.out.println(number.toString(2)); }}
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
String s = "55795556555123";
BigInteger number = new BigInteger(s);
System.out.println(number.toString(2));
}
输出:
1100101011111011101010010101000001100101110011
如果你想从 byte[] ,您可以使用 String#String(byte[]) :
byte[]
String#String(byte[])
import java.math.BigInteger;public class Main { public static void main(String[] args) { String s = "55795556555123"; byte[] array = s.getBytes(); BigInteger number = new BigInteger(new String(array)); System.out.println(number.toString(2)); }}
byte[] array = s.getBytes();
BigInteger number = new BigInteger(new String(array));
gopyfrb32#
你完全误解了什么 new BigInteger(array) 做。正如javadoc所说:将包含biginteger的二位补码二进制表示形式的字节数组转换为biginteger。输入数组假定为大端字节顺序:最高有效字节位于第0个元素中。说你的线是 s = "123456". That is hex 1e240型 , which means that the 字节[] you pass to the biginteger`构造函数应为:
new BigInteger(array)
s = "123456". That is hex
, which means that the
you pass to the
byte[] array = { 0x01, (byte) 0xE2, 0x40 };System.out.println(Arrays.toString(array)); // prints: [1, -30, 64]BigInteger number = new BigInteger(array);System.out.println(number); // prints: 123456
byte[] array = { 0x01, (byte) 0xE2, 0x40 };
System.out.println(Arrays.toString(array)); // prints: [1, -30, 64]
BigInteger number = new BigInteger(array);
System.out.println(number); // prints: 123456
但是javadoc s.getBytes() (不是 getbyte() )说:使用平台的默认字符集返回字节序列在这种情况下通常是指ascii码。
s.getBytes()
getbyte()
String s = "123456";byte[] array = s.getBytes();System.out.println(Arrays.toString(array)); // prints: [49, 50, 51, 52, 53, 54]
String s = "123456";
System.out.println(Arrays.toString(array)); // prints: [49, 50, 51, 52, 53, 54]
如你所见 byte[] 远没有达到应有的水平 BigInteger 建造师。你得打电话 new BigInteger(s) . 我怀疑你能写出一个更快的版本 String (带小数文本)到 byte[] (二进位补码二进制)转换。
BigInteger
new BigInteger(s)
String
2条答案
按热度按时间9rygscc11#
biginteger#biginteger(java.lang.string)
按以下步骤操作:
输出:
如果你想从
byte[]
,您可以使用String#String(byte[])
:输出:
gopyfrb32#
你完全误解了什么
new BigInteger(array)
做。正如javadoc所说:将包含biginteger的二位补码二进制表示形式的字节数组转换为biginteger。输入数组假定为大端字节顺序:最高有效字节位于第0个元素中。
说你的线是
s = "123456". That is hex
1e240型, which means that the
字节[]you pass to the
biginteger`构造函数应为:但是javadoc
s.getBytes()
(不是getbyte()
)说:使用平台的默认字符集返回字节序列
在这种情况下通常是指ascii码。
如你所见
byte[]
远没有达到应有的水平BigInteger
建造师。你得打电话
new BigInteger(s)
. 我怀疑你能写出一个更快的版本String
(带小数文本)到byte[]
(二进位补码二进制)转换。