Reputation: 35
BigInteger i = new BigInteger("1000");
Byte[] arr = i.toByteArray();
Contents of arr: [3, -24]
Since byte range in java is: minimum -128 and a maximum value of 127 (inclusive).
The java.math.BigInteger.toByteArray()
returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element.
How can I do this in python 2.7? Since the byte range there is 0 <= byte <= 255 e.g.
x = 1000
list = doTheMagic(x)
and as a result I get:
list = [3, -24]
Upvotes: 1
Views: 675
Reputation: 10341
user189's answer is almost correct. Sometimes BigInteger.toByteArray()
adds an extra zero byte to its result. Here's a more correct solution:
def to_byte_array(num):
bytea = []
n = num
while n:
bytea.append(n % 256)
n //= 256
n_bytes = len(bytea)
if 2 ** (n_bytes * 8 - 1) <= num < 2 ** (n_bytes * 8):
bytea.append(0)
return bytearray(reversed(bytea))
Upvotes: 0
Reputation: 604
If I understood correctly what you want, something like that could do the trick.
def doTheMagic(x):
l = []
while x:
m = x%256
l.append(m if m <=127 else m-256)
x /= 256
return l[::-1]
x = 1000
l = doTheMagic(x)
print l
Upvotes: 0
Reputation: 369164
Using struct.pack
and struct.unpack
:
>>> struct.unpack('2b', struct.pack('>h', 1000))
(3, -24)
>>> struct.unpack('4b', struct.pack('>I', 1000))
(0, 0, 3, -24)
>>> struct.unpack('8b', struct.pack('>Q', 1000))
(0, 0, 0, 0, 0, 0, 3, -24)
Unfortunately, you can't get abitrary length byte array using struct.pack
/struct.unpack
.
Upvotes: 3