Python: converting single digit decimal to hex - python

Is there any way to get hex (5) output '0x05' instead of '0x5'?
For example i want to convert [255,11,132] to hex string like 'ff0b84' So i can slice it by 2 characters and covert to decimal again. But python doesn't put 0 before b so i can't slice string by 2 characters!

I think you could use format to get '0x05' instead of '0x5':
In [64]: format(5, '#04x')
Out[64]: '0x05'
In [65]: format(15, '#04x')
Out[65]: '0x0f'

Related

Hex to a String Python

I would like to convert
the hex value
a = 0x32
to a string d = 32
Bascially I have a numpy array
msg = np.array[2, 50]
I need to convert both values to hex --- [0x02 , 0x32]
then print the hex values as strings on GUI as 2, 32
hex() will give you hex string. Then discard first 2 characters
>>> hex(a)
'0x32'
>>> hex(a)[2:]
'32'
>>>
Looking at the link to duplicate, it seems numpy is giving you the L at the end since you are running 64bit linux. so do this:
hex(a)[2:-1]

How to convert byte string with non-printable chars to hexadecimal in python? [duplicate]

This question already has answers here:
What's the correct way to convert bytes to a hex string in Python 3?
(9 answers)
Closed 7 years ago.
I have an ANSI string Ď–ór˙rXüď\ő‡íQl7 and I need to convert it to hexadecimal like this:
06cf96f30a7258fcef5cf587ed51156c37 (converted with XVI32).
The problem is that Python cannot encode all characters correctly (some of them are incorrectly displayed even here, on Stack Overflow) so I have to deal with them with a byte string.
So the above string is in bytes this: b'\x06\xcf\x96\xf3\nr\x83\xffrX\xfc\xef\\\xf5\x87\xedQ\x15l7'
And that's what I need to convert to hexadecimal.
So far I tried binascii with no success, I've tried this:
h = ""
for i in b'\x06\xcf\x96\xf3\nr\x83\xffrX\xfc\xef\\\xf5\x87\xedQ\x15l7':
h += hex(i)
print(h)
It prints:
0x60xcf0x960xf30xa0x720x830xff0x720x580xfc0xef0x5c0xf50x870xed0x510x150x6c0x37
Okay. It looks like I'm getting somewhere... but what's up with the 0x thing?
When I remove 0x from the string like this:
h.replace("0x", "")
I get 6cf96f3a7283ff7258fcef5cf587ed51156c37 which looks like it's correct.
But sometimes the byte string has a 0 next to a x and it gets removed from the string resulting in a incorrect hexadecimal string. (the string above is missing the 0 at the beginning).
Any ideas?
If you're running python 3.5+, bytes type has an new bytes.hex() method that returns string representation.
>>> h = b'\x06\xcf\x96\xf3\nr\x83\xffrX\xfc\xef\\\xf5\x87\xedQ\x15l7'
b'\x06\xcf\x96\xf3\nr\x83\xffrX\xfc\xef\\\xf5\x87\xedQ\x15l7'
>>> h.hex()
'06cf96f30a7283ff7258fcef5cf587ed51156c37'
Otherwise you can use binascii.hexlify() to do the same thing
>>> import binascii
>>> binascii.hexlify(h).decode('utf8')
'06cf96f30a7283ff7258fcef5cf587ed51156c37'
As per the documentation, hex() converts “an integer number to a lowercase hexadecimal string prefixed with ‘0x’.” So when using hex() you always get a 0x prefix. You will always have to remove that if you want to concatenate multiple hex representations.
But sometimes the byte string has a 0 next to a x and it gets removed from the string resulting in a incorrect hexadecimal string. (the string above is missing the 0 at the beginning).
That does not make any sense. x is not a valid hexadecimal character, so in your solution it can only be generated by the hex() call. And that, as said above, will always create a 0x. So the sequence 0x can never appear in a different way in your resulting string, so replacing 0x by nothing should work just fine.
The actual problem in your solution is that hex() does not enforce a two-digit result, as simply shown by this example:
>>> hex(10)
'0xa'
>>> hex(2)
'0x2'
So in your case, since the string starts with b\x06 which represents the number 6, hex(6) only returns 0x6, so you only get a single digit here which is the real cause of your problem.
What you can do is use format strings to perform the conversion to hexadecimal. That way you can both leave out the prefix and enforce a length of two digits. You can then use str.join to combine it all into a single hexadecimal string:
>>> value = b'\x06\xcf\x96\xf3\nr\x83\xffrX\xfc\xef\\\xf5\x87\xedQ\x15l7'
>>> ''.join(['{:02x}'.format(x) for x in value])
'06cf96f30a7283ff7258fcef5cf587ed51156c37'
This solution does not only work with a bytes string but with really anything that can be formatted as a hexadecimal string (e.g. an integer list):
>>> value = [1, 2, 3, 4]
>>> ''.join(['{:02x}'.format(x) for x in value])
'01020304'

format float number to 17 chars - Python

I'm new to Python, and I'm struggling to format a number to 17 chars including the decimal point.
example:
100.00
result:
0000000100.000000
I tried .zfill(17), but it only displays one digit after the decimal point.
Use str.format:
>>> '{:017.6f}'.format(100.00)
'0000000100.000000'
or format:
>>> format(100.00, '017.6f')
'0000000100.000000'
I like this:
In [42]: '%017.6f'%100
Out[42]: '0000000100.000000'

Convert hex-string to string using binascii

By hex-string, it is a regular string except every two characters represents some byte, which is mapped to some ASCII char.
So for example the string
abc
Would be represented as
979899
I am looking at the binascii module but don't really know how to take the hex-string and turn it back into the ascii string.
Which method can I use?
Note: I am starting with 979899 and want to convert it back to abc
You can use ord() to get the integer value of each character:
>>> map(ord, 'abc')
[97, 98, 99]
>>> ''.join(map(lambda c: str(ord(c)), 'asd'))
'979899'
>>> ''.join((str(ord(c)) for c in 'abc'))
'979899'
You don't need binascii to get the integer representation of a character in a string, all you need is the built in function ord().
s = 'abc'
print(''.join(map(lambda x:str(ord(x)),s))) # outputs "979899"
To get the string back from the hexadecimal number you can use
s=str(616263)
print "".join([chr(int(s[x:x+2], 16)) for x in range(0,len(s),2)])
See http://ideone.com/dupgs

hex string to character in python

I have a hex string like:
data = "437c2123"
I want to convert this string to a sequence of characters according to the ASCII table.
The result should be like:
data_con = "C|!#"
Can anyone tell me how to do this?
In Python2
>>> "437c2123".decode('hex')
'C|!#'
In Python3 (also works in Python2, for <2.6 you can't have the b prefixing the string)
>>> import binascii
>>> binascii.unhexlify(b"437c2123")
b'C|!#'
In [17]: data = "437c2123"
In [18]: ''.join(chr(int(data[i:i+2], 16)) for i in range(0, len(data), 2))
Out[18]: 'C|!#'
Here:
for i in range(0, len(data), 2) iterates over every second position in data: 0, 2, 4 etc.
data[i:i+2] looks at every pair of hex digits '43', '7c', etc.
chr(int(..., 16)) converts the pair of hex digits into the corresponding character.
''.join(...) merges the characters into a single string.
Since Python 2.6 you can use simple:
data_con = bytes.fromhex(data)
The ord function converts characters to numerical values and the chr function does the inverse. So to convert 97 to "a", do ord(97)

Categories

Resources