Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert n-byte int to bytes in python3

Tags:

python-3.x

I want to convert an 32-byte (although I might need other lengths) integer to a bytes object in python. Is there a clean and simple way to do this?

like image 427
Peter Avatar asked Jan 18 '11 21:01

Peter


People also ask

How do you convert int to bytes?

An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.

What is B '\ x00 in Python?

b means bytes , not binary. \x00 is not string 0 but char with code 0 which can't be displayed so Python shows its code. – furas.

How do you cast a byte in Python?

We can use the built-in Bytes class in Python to convert a string to bytes: simply pass the string as the first input of the constructor of the Bytes class and then pass the encoding as the second argument.

What does bytes () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.


1 Answers

to_bytes(length, byteorder[, signed]) is all you need starting from 3.2. In this case, someidentifier.to_bytes(4,'big') should give you the bytes string you need.

like image 140
SilverbackNet Avatar answered Oct 23 '22 12:10

SilverbackNet