Answers for "int to bytes python"

1

convert int to byte python

pythonCopy>>> (258).to_bytes(2, byteorder="little")
b'x02x01'
>>> (258).to_bytes(2, byteorder="big")
b'x01x02'
>>> (258).to_bytes(4, byteorder="little", signed=True)
b'x02x01x00x00'
>>> (-258).to_bytes(4, byteorder="little", signed=True)
b'xfexfexffxff'
Posted by: Guest on September-06-2020
0

python bytes to int

"""
Python 3
"""

# int.from_bytes( bytes, byteorder, *, signed=False )
# bytes must evaluate as bytes-like object
# byteorder is optional. someString must evaluate as 'big' xor 'little'
# signed is optional. someBoolean opmust evaluate as boolean


# examples: 
someBytes = b'x00x01x00x02x00x03'
someInteger = int.from_bytes(someBytes)
someInteger = int.from_bytes(someBytes, 'big')
someInteger = int.from_bytes(someBytes, byteorder='little', signed=True)


"""
Python 2.7
"""

# no bytes is str in Python 2.7

import struct
struct.unpack(pattern, someBytes) 

# someBytes is of type str or byte array

# pattern is a string begining with '>' or '<', 
# followed by as many 'H' or 'B' chars needed 
# to cover the someBytes' length. 

# '>' stands for Big-endian
# '<' stands for Big-endian
# 'H' stands for 2 bytes unsigned short integer
# 'B' stands for 1 byte  unsigned char


# examples: 

>>> import struct
>>> sixBytes = b'x00x01x00x02x00x03'
>>> struct.unpack('>HHH', sixBytes)
(1, 2, 3)

>>> struct.unpack('<HHH', sixBytes)
(256, 512, 768)

>>> struct.unpack('>BBBBBB', sixBytes)
(0, 1, 0, 2, 0, 3)

>>> struct.unpack('<BBBBBB', sixBytes)
(0, 1, 0, 2, 0, 3)
Posted by: Guest on December-02-2020

Python Answers by Framework

Browse Popular Code Answers by Language