Python bytearray to float

How to Convert a Byte array to Float in Python : 4 Steps

Concatenate Two Arrays Python into a List

Do you want to convert a byte array to float in Python? If yes then you have come to the right place. In this post, you will know how to convert a byte array to float in Python using steps.

Steps to convert a byte array to float in Python

Let’s know all the steps you will follow to convert the byte array to float in Python.

Step 1: Import the required library

The first step is to import all the required libraries for the implementation of the example. In our example, I am using only the struct module. So let’s import it using the import statement.

Step 2: Create a sample byte array

The second step is to create a sample byte array that will use in the future to convert it into float.

The following line of code will use for byte array creation.

Читайте также:  Padding left and right in css

Step 3: Convert the byte array to the binary string

The next step is to first convert the byte array to a binary string. To do this you have to use the join() function with the ‘b’. The byte array is passed as an argument for the join() function.

Use the below line of code to convert the byte array to a binary string.

Step 4: Convert the binary string to float

Now the final step is to convert the binary string to a byte array. For this, you will use the struct.unpack() function. You will pass two arguments. One is the ‘

The output you will get is an array. You have to select the first element.

Add the below line of code for the conversion.

convert byte array to float

Output

Conclusion

Converting a byte array to float has many use cases. It helps you in dealing with binary data or network communications. Other use cases are File I/O for reading and writing binary data to files and Data Parsing and Interpretation. The above steps will convert the byte array to float in Python.

I hope you have liked this tutorial. If you have any queries then you can contact us for more help.

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Источник

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

  1. '?' 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.
  2. 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.
  3. 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.
  4. 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.
  5. '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.
  6. 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

  • 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

Источник

Оцените статью