python3 byte, int, str conversion

. 1  # bytes and int 
2 B = B ' \ X01 \ X02 ' 
. 3 NUM = int.from_bytes (B, ' Little ' )
 . 4  Print ( ' bytes transferred int: ' , NUM)
 . 5  
. 6 B1 = num.to_bytes (2, ' Little ' )
 . 7  Print ( ' int transfer bytes: ' , B1)
 . 8  
. 9  # bytes hexadecimal String 
10 HS = '' .join ([ ' % 02X ' % X   for X inB])
 . 11  Print ( ' bytes transferred hexadecimal string: ' , HS)
 12 is BS = bytes.fromhex (HS)
 13 is  Print ( ' hexadecimal string transfer bytes: ' , BS)
 14  # Print ( bytes.fromhex (hex (78) [2:])) 
15  
16  # int and string 
. 17 S = ' ABCD ' 
18 is NUM = int (S, 16 )
 . 19  Print ( ' string rotation int: ' , NUM)
 20 is  Print ( ' int hexadecimal string rotation: ' , hex (NUM))

Output:

bytes transferred int: 513
int transfer bytes: b '\ x01 \ x02 '
bytes transferred hexadecimal string: 0102
hexadecimal string transfer bytes: b '\ x01 \ x02 '
string transfected int: 43981
int turn hexadecimal string: 0xabcd

 
Other conversion:
int (x [, base]) will be converted to an integer x    
long (x [, base]) will be converted to a long integer x    
a float (x) to convert to a floating-point number x      
STR (x) will be converted to a string object x    
eval (str) used to calculate the effective string Python expression and returns an object    
tuple (s) to convert the sequence s is a tuple    
List (s) to convert the sequence s is a list of    
chr (x) to convert an integer to a character    
ord (x) to convert a character to its integer value    
hex (x) to convert an integer to a hexadecimal string    
oct (x) to convert an integer to an octal string 
 

The following are the bytes syntax:

class bytes([source[, encoding[, errors]]])

parameter

  • If the source is an integer, it returns an array of length initialization of the source;
  • If the source is a string, then the specified encoding the string into a sequence of bytes;
  • If the source type to be iterative, the element must be an integer [0, 255] in;
  • If the source is coincident with buffer interface object, this object can also be used to initialize bytearray.
  • If you do not enter any parameters, the default is to initialize the array is 0 element.

 

 

Guess you like

Origin www.cnblogs.com/DirWang/p/11426517.html