Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using below function in Python

str(length).zfill(2).decode('hex')


Am exepcting Output as '\x0A'

But value which am getting is '\x10'

What is wrong with above program

What I have tried:

I tried using hex(length)

But it gives me '0xa' which is wrong
Posted
Updated 4-Dec-19 22:15pm
Comments
CPallini 5-Dec-19 2:58am    
It is not clear what do you want to accomplish. What is your input value?
Member 11520335 5-Dec-19 3:50am    
Input value is 10. I mean length

1 solution

the string.decode('hex') method goes in the opposite direction. You should use the hex function[^] instead. There is one caveat, though, to zero-fill it, you have to remove (and restore it afterwards) the leading '0x'. Try
Python
length=10;
s = '0x' + hex(length)[2:].zfill(2)
print(s)



[update]
Both
Python
length=10;
s = '\\x' + hex(length)[2:].upper().zfill(2)
print(s)
and (the possibly clearer)
Python
length=10
s="\\x{0:02X}".format(length)
print(s)

produce
\x0A
[/update]
 
Share this answer
 
v2
Comments
Member 11520335 5-Dec-19 7:01am    
But this results in
'0x0a'

But i need like below
'\x0A'
CPallini 5-Dec-19 7:26am    
I've updated my solution, have a look at it, now.
Member 11520335 6-Dec-19 0:07am    
Even i tried your first updated solution. It results in

'\\x0A'

Second solution gives me the same output as provious

It should be '\x0A'
CPallini 6-Dec-19 3:09am    
You are wrong:
https://tio.run/##K6gsycjPM/r/Pyc1L70kw9bQgKvYVikmpqLawMrAKKJWSS8tvyg3sUQDIq/JVVCUmVeiUaz5/z8A
Member 11520335 8-Dec-19 0:13am    
may be online Tutor gives the proper values .
But am running this code whith jetBrains Pycharm as IDE
Python Version 3.8.0
Am still getting wrong value
'\\x0A'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900