hex int and string

Peter Otten __peter__ at web.de
Fri Nov 27 04:48:33 EST 2009


luca72 wrote:

> i'm using pyscard
> 
> and for send a command he need a list like this:
> 
> cmd = [0xdd,0xff, etc]

Note that 0xdd is exactly the same as 221:

>>> 0xdd == 221
True

It's just an alternative way to write an integer literal that is sometimes 
more convenient. Therefore you don't need the final hex() call; just

s = "D3"
v = int(s, 16)

is enough. To build a cmd list from a list of strings use

>>> string_cmd = ["D3", "FF"]
>>> cmd = [int(s, 16) for s in string_cmd]
>>> cmd
[211, 255]

Again, cmd looks different but is exactly the same as [0xd3, 0xff]:

>>> cmd == [0xd3, 0xff]
True

> the problem is that i get a text
> like dd
> and i need to trasform it in 0xdd for the list and if i use hex i have
> a sting that is not what i need
> 
> Luca
> 
> On 27 Nov, 10:22, Ben Finney <ben+pyt... at benfinney.id.au> wrote:
>> luca72 <lucabe... at libero.it> writes:
>> > str = 'D3'
>>
>> Be careful when choosing names. Here you have clobbered the existing
>> string type binding to the name ‘str’.
>>
>> > and i need to trasform in 0xd3 type int and not type string how i can
>> > do this?
>>
>> You already have the answer; you used it in your example below. I can
>> only assume you're wanting something additional; what is that?
>>
>> > if i do hex(int(str,16) ) i obtain a string and this is not what i
>> > need.
>>
>> You either want it as an int, or you want it as a string. Which is it?
>>
>> >>> foo = 'D3'
>> >>> int(foo, 16)
>> 211
>> >>> 0xD3
>> 211
>> >>> int(foo, 16) == 0xD3
>> True
>>
>> --
>> \            “Human reason is snatching everything to itself, leaving |
>> `\                     nothing for faith.” —Saint Bernard, 1090–1153 |
>> _o__)                                                                  |
>> Ben Finney





More information about the Python-list mailing list