I am quite new in Python and I am looking for converting numbers from decimal to hex How to convert float numbers to hex or char in Python 2.4.3? how can I keep it to write it as ("\xa5\x (here the new hex number)")
any help Thanks,
I am quite new in Python and I am looking for converting numbers from decimal to hex How to convert float numbers to hex or char in Python 2.4.3? how can I keep it to write it as ("\xa5\x (here the new hex number)")
any help Thanks,
You can't convert a float directly to hex. You need to convert to int first.
hex(int(value))
Note that int always rounds down, so you might want to do the rounding explicitly before converting to int:
hex(int(round(value)))
From python 2.6.5 docs in hex(x) definition:
To obtain a hexadecimal string representation for a float, use the float.hex() method.
Judging from this comment:
would you mind please to give an example of its use? I am trying to convert this 0.554 to hex by using float.hex(value)? and how can I write it as (\x30\x30\x35\x35)? – jordan2010 1 hour ago
what you really want is a hexadecimal representation of the ASCII codes of those numerical characters rather than an actual float represented in hex.
"5" = 53(base 10) = 0x35 (base 16)
You can use ord() to get the ASCII code for each character like this:
>>> [ ord(char) for char in "0.554" ]
[48, 46, 53, 53, 52]
Do you want a human-readable representation? hex() will give you one but it is not in the same format that you asked for:
>>> [ hex(ord(char)) for char in "0.554" ]
['0x30', '0x2e', '0x35', '0x35', '0x34']
# 0 . 5 5 4
Instead you can use string substitution and appropriate formatters
res = "".join( [ "\\x%02X" % ord(char) for char in "0.554" ] )
>>> print res
\x30\x2E\x35\x35\x34
But if you want to serialize the data, look into using the struct
module to pack the data into buffers.
edited to answer jordan2010's second comment
Here's a quick addition to pad the number with leading zeroes.
>>> padded_integer_str = "%04d" % 5
>>> print padded_integer_str
0005
>>> res = "".join( [ "\\x%02X" % ord(char) for char in padded_integer_str] )
>>> print res
\x30\x30\x30\x35
See http://docs.python.org/library/stdtypes.html#string-formatting for an explanation on string formatters
Thanks Jeremy for your help.
May I ask here….. I wrote this ("\xf3\x30\x31\x39\x39\x0d")
manually in an array and gave me this (ó0199)
when I asked the software to print it to me. This also working fine to my serial port and it sent the correct number.
Now, I did the following :
res1 = "".join( ["\\x%02X"% ord(char) for char in "1000" ] )
res2=str("\\xf3")+res1+str("\\x0d")
print res2 #res2=\xf3\x31\x30\x30\x30\x0d
but when I sent this over the serial port I have got this (64 5C 78 66 33 5C 78 33 31 5C 78 33 30 5C 78 33 30 5C 78 33 30 5C 78 30 64 )
through serial port monitor, which this data is wrong it should be 1
Any idea how can I send res2 over serial port?