How to convert a "long in a string" to a "long"?

O

ondekoza

Hello,

I need to convert the string "FFFFFFFF" to a long. To convert this
string I tried the following:4294967295L

OK, this is what I want, so I tried

s = long("0xffffffffL")
ValueError: invalid literal for long(): 0xffffffffL

s = long("0xffffffff")
ValueError: invalid literal for long(): 0xffffffffL

What can I do?

Thank you in advance.
Stefan
 
C

Carsten Haese

Hello,

I need to convert the string "FFFFFFFF" to a long. To convert this
string I tried the following:
4294967295L

OK, this is what I want, so I tried

s = long("0xffffffffL")
ValueError: invalid literal for long(): 0xffffffffL

s = long("0xffffffff")
ValueError: invalid literal for long(): 0xffffffffL

What can I do?

Thank you in advance.
Stefan

Leave out the "0x" prefix and tell long() that you're using base 16:
4294967295L

HTH,

Carsten.
 
K

Klaus Alexander Seistrup

Carsten said:
Leave out the "0x" prefix and tell long() that you're using
base 16:

4294967295L

It's sufficient to tell long() that you're using base 16:

#v+

#v-

Cheers,
 
L

Leif K-Brooks

Sion said:
So why does the base argument to int() (or long()) default to
10 and not 0?

Because it's designed for numbers normal people provide, not for numbers
programmers provide. Normal people see 0123 as being equal to 123, not 83.
 
S

Steven D'Aprano

Leave out the "0x" prefix and tell long() that you're using base 16:

4294967295L


Or leave the prefix in, and tell Python to use the prefix to predict the
base:

py> long("0xffffffffL", 0)
4294967295L
 
S

Steven D'Aprano

Because it's designed for numbers normal people provide, not for numbers
programmers provide. Normal people see 0123 as being equal to 123, not 83.

The base arguments to int() and long() default to base 10 because base 10
is used by just about all people and cultures in the world. Leading zeroes
are mathematically meaningless: 0123 means 0*base**3 + 1*base**2 +
2*base**1 + 3*base**0, which is identical to 123 no matter what base you
choose.

Interpreting 0123 in octal is a sop to programmers who want/need
compatibility to the C bug that changes the meaning of numeric literals
according to the presence or absence of a leading zero. Alas I suspect
that this particular piece of illogic is too ingrained now to ever
eradicate.
 
O

ondekoza

Thank you, for all the good answers. Somehow I overlooked the 'radix'
option in the docs.

S
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top