将字节转换为int并返回java / python

时间:2019-05-06 13:31:07

标签: java python int byte

我正在转换一个任意的ascii字符串,它是一个用零填充的数字,例如“ 1”为“ 0000000001”,然后转换为字节,然后返回python。当然,该值也可以是“ 0000004231”等。它始终是数字,并且在带零填充的有符号32位值的范围内。

当我告诉python它是字节并且我想要int时,它将其转换为一个不错的大随机数。然后,我稍后可以使用to_bytes()函数将其转换回原始值。

In [74]: value = int.from_bytes(bytes(format(1, '010d'),'ascii'), byteorder='little')                                                                                                                                                                                          

In [75]: value.to_bytes(10,byteorder=sys.byteorder)                                                                                                                                                                                                                            
Out[75]: b'0000000001'

In [76]: value                                                                                                                                                                                                                                                                 
Out[76]: 232284873704446901628976

In [77]: 

如何用Java实现相同目的?

2 个答案:

答案 0 :(得分:0)

Java代码的精确(?)功能副本:

String string = String.format("%010d", 1); // I hope this format is correct

byte[] bigEndian    = string.getBytes(StandardCharsets.US_ASCII);
System.out.println(Arrays.toString(bigEndian)); // [48, 48, 48, 48, 48, 48, 48, 48, 48, 49]

byte[] littleEndian = new byte[bigEndian.length];
for (int i = 0; i < bigEndian.length; i++)
    littleEndian[littleEndian.length - i - 1] = bigEndian[i];

BigInteger value = new BigInteger(littleEndian);
System.out.println(value); // 232284873704446901628976

然后返回:

BigInteger value = new BigInteger("232284873704446901628976");

byte[] littleEndian = value.toByteArray();

byte[] bigEndian = new byte[littleEndian.length];
for (int i = 0; i < littleEndian.length; i++)
    bigEndian[bigEndian.length - i - 1] = littleEndian[i];

System.out.println(Arrays.toString(bigEndian)); // [48, 48, 48, 48, 48, 48, 48, 48, 48, 49]

String string = new String(bigEndian, StandardCharsets.US_ASCII);
System.out.println(string); // 0000000001

int number = Integer.parseInt(string);
System.out.println(number); // 1

无论如何,如果使python代码使用big-endian,则可以跳过Java中的数组反转。

答案 1 :(得分:-1)

我对Python不好,但也许像这样:

String test = "0000000001";
byte[] testBytes = test.getBytes(); // If needed pass an encoding as argument
String newTest = new String(testBytes); // Again, if needed, pass an encoding as argument