- Python 3 data type conversion
- Summary of data type conversion support
- Conversion instance
- Convert to int
- Convert to float
- Convert to bool
- Convert to complex
- Convert to string
- Convert to bytes
- Convert to list
- Convert to tuple
- Convert to set
- Convert to dict
- bytearray ⇋ hex
- bytearray ⇋ int
- bytearray ⇋ str
- appendix
- Popular Keywords
- Convert Bytes to Int in Python 2.7 and 3.x
- Python 2.7 Bytes Data Type
- Convert Byte to Int in Python 2.7
- struct Examples: Convert Byte to Int in Python 2.7
- Python 3 Bytes Data Type
- Convert Bytes to Int in Python 3
- int.from_bytes() Examples: Convert Byte to Int
- Use [] When Bytes Is unsigned char
- Related Article - Python Bytes
Python 3 data type conversion
Data type conversion refers to the conversion of one data type from the original type to another through some method. For example, we convert the string «123» to the number 123, which is a data type conversion.
Python supports the conversion between various standard data types, but not any data can be converted. All conversions should comply with «common sense» and should be logically valid. For example, you shouldn’t try to convert a complex type to int, because Python doesn’t know how to convert it.
Summary of data type conversion support
Int | Float | Bool | Complex | String | Bytes | List | Tuple | Set | Dict | |
---|---|---|---|---|---|---|---|---|---|---|
Int | — | Y | Y | N | Y | Y | N | N | N | N |
Float | Y | — | Y | N | Y | Y | N | N | N | N |
Bool | Y | Y | — | Y | Y | Y | Y | Y | Y | Y |
Complex | Y | Y | Y | — | Y | N | N | N | N | N |
String | Y | Y | Y | Y | — | Y | Y | Y | Y | Y |
Bytes | Y | N | Y | N | Y | — | Y | Y | Y | N |
List | N | N | N | N | Y | Y | — | Y | Y | Y |
Tuple | N | N | N | N | Y | Y | Y | — | Y | Y |
Set | N | N | N | N | Y | Y | Y | Y | — | Y |
Dict | N | N | N | N | Y | N | Y | Y | Y | — |
Note: Bytes only considers direct conversion
Conversion instance
Convert to int
print(int(1.2)) # float -> int print(int('123')) # string -> int print(int(b'456')) # bytes -> int print('0x%x' % (int.from_bytes(b'456', byteorder='little', signed=True))) print(int(True)) # bool -> int
Convert to float
print(float('1.2')) # string->float print(float(b'3.4')) # bytes -> float print(float(123)) # int->float print(float(False)) # bool->float
Convert to bool
# All types can be converted to bool print(bool(1)) # int->bool print(bool(0.0)) # float->bool print(bool(0 + 0j)) # complex->bool print(bool('')) # String - > bool, empty string is False, others are True print(bool(b'hello')) # Bytes - > bool, null is False, others are True print(bool.from_bytes(b'\x00', byteorder='little')) # bytes->bool print(bool([])) # List - > bool, null is False, others are True print(bool(())) # Tuple - > bool, null is False, others are True print(bool(<>)) # Dict - > bool, null is False, others are True print(bool(set())) # Set - > bool, null is False, others are True
Convert to complex
print(complex(100)) # int->complex print(complex(1.2)) # float->complex print(complex(True)) # bool->complex print(complex('1.2+2.3j')) # string->complex
Convert to string
# All basic types can be converted to string print(b'hello'.decode('utf-8')) # bytes->string print(str(1)) # int->string print(str(1.2)) # float->string print(str(True)) # bool->string print(str(1.2 + 2.3j)) # Complex - > string all others are True print(str(['hello', 100])) # list->string print(str(('hello', 100))) # tuple->string print(str()) # dict->string print(str()) # set->string
Convert to bytes
# Because all types can be converted to string and string can be converted to bytes, all types can be indirectly converted to bytes. # Next, we will only discuss the type directly converted to bytes print('bytes'.center(30, '*')) print(b'\x64') # int to bytes print(int.to_bytes(100, byteorder='big', signed=True, length=2)) # int to bytes print(bool.to_bytes(True, byteorder='big', signed=True, length=2)) # bool to bytes print('hello'.encode(encoding='utf-8')) # string to bytes print(bytes([1, 200, 80, 50])) # list to bytes print(bytes((1, 200, 80, 50))) # tuple to bytes print(bytes()) # set to bytes
Convert to list
print(list("hello")) # string->list print(list(b'hello')) # bytes->list print(list((100, 200, 300))) # tuple->list print(list()) # set->list print(list()) # Dict - > list, only the key value is taken
Convert to tuple
print(tuple("hello")) # string->tuple print(tuple(b"hello")) # bytes->tuple print(tuple([100, 200, 300])) # list->tuple print(tuple()) # set->tuple print(tuple()) # Dict - > tuple, only the key value is taken
Convert to set
print(set("hello")) # string->set print(set(b"hello")) # bytes->set print(set([100, 200, 300])) # list->set # print(set([100, 200, [300, 400]])) # List - > set, the list contains variable data types, and an exception is reported print(set(('name', 'age'))) # tuple->set # print(set(('name', 'age', []))) # Tuple - > set, including variable data types, and an exception is reported print(set()) # Dict - > set, only the key value is taken
Convert to dict
# Method 1: use json conversion. The string format needs to be strictly in accordance with the json format user_str = '' import json print(json.loads(user_str)) # Mode 2. Use eval function conversion. eval has potential safety hazards and is not recommended print(eval(user_str)) # Method 3: use ast.literal_eval import ast print(ast.literal_eval(user_str))
# Method 1. zip is required user_keys = ['name', 'city', 'age'] user_values = ['xiaowang', 'Chengdu', 28] print(dict(zip(user_keys, user_values))) # Mode 2: 2D list user_info = [ ["name", "xiaowang"], ["city", "Chengdu"], ["age", 28] ] print(dict(user_info))
Set — > dict tuple — > dict is the same as list — > dict
bytearray ⇋ hex
# hex_str-->bytearray byte_array = bytearray.fromhex("050460000008d40462000007670463") print(byte_array) # bytearray-->hex_str hex_str = byte_array.hex() print(hex_str)
# hex_str-->bytearray byte_array = bytearray.fromhex("05 04 60 00 00 08 d4 04 62 00 00 07 67 04 63") print(byte_array) # bytearray-->hex_str hex_str = byte_array.hex() hex_str_space = " ".join([hex_str[i - 1:i + 1] if i % 2 else "" for i in range(len(hex_str))]).strip() print(hex_str_space)
bytearray ⇋ int
import struct # int-->bytearray bytearray_short = struct.pack("int int_short = struct.unpack(" bytearray ⇋ str
# str-->bytearray byte_array = bytearray("liuyang", encoding='utf-8') print(byte_array) # bytearray-->str st_r = byte_array.decode('utf-8') print(st_r)appendix
- '?' The conversion code corresponds to the conversion code defined by C99_ Bool type. If this type is not available, use char to simulate. In standard mode, it is always represented in one byte.
- When attempting to package a non integer with any integer conversion code, if the non integer has __index__() Method calls the method before packing and converts the parameter to an integer. Change in version 3.2: added use for non integer __index__() Method.
- The 'N' and 'N' conversion codes are only available for native size (select as default or use '@' byte order characters). For standard sizes, you can use any other integer format suitable for your application.
- For 'f','d 'and' e 'conversion codes, the packaged representation will use IEEE 754 binary32, binary64 or binary16 format (corresponding to' f ','d' or 'e' respectively), regardless of the floating-point format used by the platform.
- 'P' format characters are only available for native byte order (select as default or use '@' byte order characters). The byte order character '=' selects to use the small end or large end sorting based on the host system. The struct module will not interpret it as a native sort, so the 'P' format will not be available.
- IEEE 754 binary16 "half precision" type is in IEEE 754 standard Introduced in the 2008 revision of. It contains one sign bit, five exponential bits and 11 precision bits (10 bits are explicitly stored), which can completely and accurately represent numbers in the approximate range of 6.1e-05 and 6.5e+04. This type is not widely supported by the C compiler: on a typical machine, unsigned short can be used for storage, but it will not be used for mathematical operations. See Wikipedia page half-precision floating-point format Learn more.
Added by peaforabrain on Wed, 10 Nov 2021 17:15:29 +0200
Popular Keywords
- Java - 6234
- Python - 2579
- Javascript - 2100
- Database - 1608
- Linux - 1477
- Back-end - 1449
- Front-end - 1432
- Spring - 1358
- Algorithm - 1311
- Android - 1124
- MySQL - 1040
- C++ - 1022
- Programming - 966
- network - 827
- data structure - 820
- Attribute - 785
- C - 721
- github - 646
- less - 645
- SQL - 639
Convert Bytes to Int in Python 2.7 and 3.x
Craving a more dynamic learning experience? we've crafted a comprehensive YouTube video complementing this article embedded at the end of this page!
Bytes data type has the value with a range from 0 to 255 (0x00 to 0xFF). One byte has 8 bits; that’s why its maximum value is 0xFF. In some circumstances, you need to convert bytes or bytes array to integers for further data processing. This short article introduces methods to convert byte to int in Python, like the struct.unpack method in Python 2.7 and int.from_bytes() in Python 3.x.
Python 2.7 Bytes Data Type
There is no built-in bytes data type in Python 2.7 version. Keyword byte is identical to str .
bytearray is used to define a bytes or byte array object.
>>> byteExample1 = bytearray([1]) >>> byteExample1 bytearray(b'\x01') >>> byteExample2 = bytearray([1,2,3]) >>> byteExample2 bytearray(b'\x01\x02\x03')
Convert Byte to Int in Python 2.7
Python internal module struct could convert binary data (bytes) to integers. It could convert bytes or actually strings in Python 2.7 and integers in a bidirectional way.
struct.unpack(fmt, string) Convert the string according to the given format `fmt` to integers. The result is a tuple even if there is only one item inside.
struct Examples: Convert Byte to Int in Python 2.7
import struct testBytes = b'\x00\x01\x00\x02' testResult = struct.unpack('>HH', testBytes) print testResult
- > indicates the binary data is big-endian , or in other words, the data is ordered from the big end (most significant bit). For example, \x00\0x1 means \x00 is the high byte, and \x01 is the low byte.
- HH means there are two objects of H types in the bytes string. H represents an unsigned short integer that takes 2 bytes.
You could get different results from the same string if the assigned data format is different.
>>> testResult = struct.unpack(', testBytes) >>> testResult (256, 512)
>>> testResult = struct.unpack(', testBytes) >>> testResult (0, 1, 0, 2)
B means the data is unsigned char taking 1 byte. Hence, \x00\x01\x00\x02 will be converted to 4 values of unsigned char , but not 2 values of unsigned short anymore.
The data length represented by the format string shall be the same as the given data; otherwise, it reports an error.
>>> testResult = struct.unpack(', b'\x00\x01\x00\x02') Traceback (most recent call last): File "", line 1, in module> testResult = struct.unpack(', b'\x00\x01\x00\x02') error: unpack requires a string argument of length 3
You could check the struct module’s official document to get more information on format strings.
Python 3 Bytes Data Type
bytes is a built-in data type in Python 3; therefore, you could define bytes directly using the bytes keyword.
>>> testByte = bytes(18) >>> type(testByte) class 'bytes'>
You could also directly define a bytes or bytes array like below.
>>> testBytes = b'\x01\x21\31\41' >>> type(testBytes) class 'bytes'>
Convert Bytes to Int in Python 3
Besides the struct module as already introduced in Python 2.7, you could also use a new Python 3 built-in int method to do the bytes-to-integers conversions, that is, the int.from_bytes() method.
int.from_bytes() Examples: Convert Byte to Int
>>> testBytes = b'\xF1\x10' >>> int.from_bytes(testBytes, byteorder='big') 61712
The byteorder option is similar to struct.unpack() format byte order definition.
int.from_bytes() has a third option signed to assign the integer type to be signed or unsigned .
>>> testBytes = b'\xF1\x10' >>> int.from_bytes(testBytes, byteorder='big', signed=True) -3824
Use [] When Bytes Is unsigned char
If the format of data has the format of unsigned char containing only one byte, you could directly use object index to access and get the integer of the data.
>>> testBytes = b'\xF1\x10' >>> testBytes[0] 241 >>> testBytes[1] 16
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
Related Article - Python Bytes