I am converting an arbitrary ascii string, which is incidently a number padded with zeros, for example "1" as "0000000001" then to bytes then back in python. Of course the value can be "0000004231" etc. also. It is always numeric and within range of signed 32bit value padded by zeros.

When I tell python that it is bytes and I want it in int, it converts it to a nice large random looking number. Then I can convert it back to original value later using to_bytes() function.

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]: 

How can I achieve same with java?

2 Answers

0
Mark Jeronimus On Best Solutions

Exact(?) functional replica of your code in 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

And back:

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

In any case, if you make the python code use big-endian, you can skip the array reversals in Java.

-1
Community On

I'm no good with Python, but perhaps something like this:

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