Lesson basis python - packing and unpacking from a string of large integers (white piao share)

# 4, the packing and unpacking large integer string
# unpack a string into a large integer, a large integer into a packed string
# 4.1 Solution:
# Suppose processing program requires a 16-byte elements string 128 which holds a large integer
Data = B '\ xOO \ x124V \ x00x \ X90 \ xab \ xOO \ XCD \ XeF \ X01 \ xOO # \ X004'
# to interpreted byte integers can be used int.from_bytes (), and then to develop endian:
Print (int.from_bytes (Data, 'Little')) # 69120565665751139577663547927094891008
Print (int.from_bytes (Data, 'big')) 94522842520747284487117727783387188 #
# to convert a large integer byte string can use int.to_bytes () method, only need to specify the number of bytes and the byte order to
X = 94522842520747284487117727783387188
Print (x.to_bytes (16, 'Big')) # B '\ xOO \ x124V \ x00x \ X90 \ xab \ xOO \ XCD \ XeF \ X01 \ xOO # \ X004 '
Print (x.to_bytes (16,' Little ')) # B'4 \ xOO # \ xOO \ X01 \ XeF \ XCD \ xOO \ xab \ x90x \ x00V4 \ X12 \ xOO '
# 4.2 discussion:
# If you try to integer packed into a string of bytes, but the byte size of inappropriate will get an error message.
# If necessary, you can use int.bit_length () to determine how many bits need to use in order to preserve the value of
the X-23 = 523 **
# x.to_bytes (16, 'Little') # OverflowError: int TOO Big to Convert For
Print ( x.bit_length ()) 'bit #: 208
nbytes, REM = divmod (x.bit_length (),. 8) # divmod (a, b) to give a, b of the quotient and the remainder consisting tuple

if rem: # can store a byte 8bit, if the remainder is 0 just able to save, save one byte or extended residual bits
nbytes + =. 1
Print (x.to_bytes (nbytes, 'Little')) # B ' \ x03X \ xf1 \ x82iT \ x96 \ xac \ xc7c \ x16 \ xf3 \ xb9 \ xcf \ x18 \ xee \ xec \ x91 \ xd1 \ x98 \ xa2 \ xc8 \ xd9R \ xb5 \ xd0 '

Published 17 original articles · won praise 1 · views 359

Guess you like

Origin blog.csdn.net/weixin_43520503/article/details/104394471