Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 equivalent of Python 2 str.decode('hex') [duplicate]

I'm trying to convert IEEE 754 floats in hex to standard python floats.

The following works in Python 2.x :

foo ='4074145c00000005'
conv_pound = struct.unpack('!d', foo.decode('hex'))[0]
print(conv_pound)

and produces the following output (which is indeed the number that I want):

321.272460938

However, python 3 does not have a str.decode method and I'm struggling to find how to do this. Any tips ?

like image 665
user3352975 Avatar asked Nov 19 '18 15:11

user3352975


People also ask

What is the difference between text encoding in Python 2 and Python 3?

In Python 3, we use "string". encode() and "string". decode() to convert an Unicode string to a bytes string, or convert a bytes string to an Unicode string. In Python 2, we have str() and unicode() , we can encode() and decode() to them, too.

How do you print a hex value of a string in Python?

hex() function in Python hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.

How do I encode a hex in python?

To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.


1 Answers

bytes.fromhex() worked for me in python3:

Python 3.6.6 (default, Sep 12 2018, 18:26:19) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> foo ='4074145c00000005'
>>> import struct
>>> struct.unpack('!d', bytes.fromhex(foo))
(321.2724609375003,)
>>> struct.unpack('!d', bytes.fromhex(foo))[0]
321.2724609375003
like image 160
Satevg Avatar answered Oct 07 '22 08:10

Satevg