I am a newbie in python.
Can some one advice how can I convert a hex number to its string representation.I would like to implement something like below.What should be the best method for 'convert()'?
val_hex = 0xBEEF
val_str = convet(val_hex) # val_str = 'BEEF'
Could using builtin function hex, which convert an integer number (of any size) to a lowercase hexadecimal string prefixed with “0x”
hex(val_hex) # ==> 0xbeef
Or using format % values, X means signed hexadecimal (uppercase)
'%X' % val_hex # ==> BEEF
Related
How to convert hexadecimal value 0x000F into string value "0F" in python? Basically, I've been trying to convert number to string.
Use % formatting:
str = "%02x" % 0x000F
%x formatting means to format as a float, the 02 prefix means to put it in a 2-digit field with zero padding.
I want to convert a hex string to utf-8
a = '0xb3d9'
to
동 (http://www.unicodemap.org/details/0xB3D9/index.html)
First, obtain the integer value from the string of a, noting that a is expressed in hexadecimal:
a_int = int(a, 16)
Next, convert this int to a character. In python 2 you need to use the unichr method to do this, because the chr method can only deal with ASCII characters:
a_chr = unichr(a_int)
Whereas in python 3 you can just use the chr method for any character:
a_chr = chr(a_int)
So, in python 3, the full command is:
a_chr = chr(int(a, 16))
Consider an integer 2. I want to convert it into hex string '0x02'. By using python's built-in function hex(), I can get '0x2' which is not suitable for my code. Can anyone show me how to get what I want in a convenient way? Thank you.
integer = 2
hex_string = '0x{:02x}'.format(integer)
See pep 3101, especially Standard Format Specifiers for more info.
For integers that might be very large:
integer = 2
hex = integer.to_bytes(((integer.bit_length() + 7) // 8),"big").hex()
The "big" refers to "big endian"... resulting in a string that is aligned visually as a human would expect.
You can then stick "0x" on the front if you want.
hex = "0x" + hex
>>> integer = 2
>>> hex_string = format(integer, '#04x') # add 2 to field width for 0x
>>> hex_string
'0x02'
See Format Specification Mini-Language
I am currently trying to find a way to convert any sort of text to a number, so that it can later be converted back to text.
So something like this:
text = "some string"
number = somefunction(text)
text = someotherfunction(number)
print(text) #output "some string"
If you're using Python 3, it's pretty easy. First, convert the str to bytes in a chosen encoding (utf-8 is usually appropriate), then use int.from_bytes to convert to an int:
number = int.from_bytes(mystring.encode('utf-8'), 'little')
Converting back is slightly trickier (and will lose trailing NUL bytes unless you've stored how long the resulting string should be somewhere else; if you switch to 'big' endianness, you lose leading NUL bytes instead of trailing):
recoveredstring = number.to_bytes((number.bit_length() + 7) // 8, 'little').decode('utf-8')
You can do something similar in Python 2, but it's less efficient/direct:
import binascii
number = int(binascii.hexlify(mystring.encode('utf-8')), 16)
hx = '%x' % number
hx = hx.zfill(len(hx) + (len(hx) & 1)) # Make even length hex nibbles
recoveredstring = binascii.unhexlify(hx).decode('utf-8')
That's equivalent to the 'big' endian approach in Python 3; reversing the intermediate bytes as you go in each direction would get the 'little' effect.
You can use the ASCII values to do this:
ASCII to int:
ord('a') # = 97
Back to a string:
str(unichr(97)) # = 'a'
From there you could iterate over the string one character at a time and store these in another string. Assuming you are using standard ASCII characters, you would need to zero pad the numbers (because some are two digits and some three) like so:
s = 'My string'
number_string = ''
for c in s:
number_string += str(ord(c)).zfill(3)
To decode this, you will read the new string three characters at a time and decode them into a new string.
This assumes a few things:
all characters can be represented by ASCII (you could use Unicode code points if not)
you are storing the numeric value as a string, not as an actual int type (not a big deal in Python—saves you from having to deal with maximum values for int on different systems)
you absolutely must have a numeric value, i.e. some kind of hexadecimal representation (which could be converted into an int) and cryptographic algorithms won't work
we're not talking about GB+ of text that needs to be converted in this manner
I trying to convert numbers from decimal to hex. How do I convert float values to hex or char in Python 2.4.3?
I would then like to be able to print it as ("\xa5\x (new hex number here)"). How do I do that?
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
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)))