Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to its Base-10 representation?

Is there any python module that would help me to convert a string into a 64-bit integer? (the maximum length of this string is 8 chars, so it should fit in a long).

I would like to avoid having to write my own method.

Example:

Input String   Hex          result (Base-10 Integer)
'Y'            59           89
'YZ'           59 5a        22874
...
like image 958
E.Z. Avatar asked May 23 '12 09:05

E.Z.


People also ask

How do you represent a base 10 in Python?

The log10() method returns base-10 logarithm of x for x > 0.

Which function converts a string to a number representation?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

How do you convert a base 10 number to another base in C++?

int x, y, a = 0, i, t, j; cout << "enter two numbers" << endl; cin >> x >> y; // x as the number in base-10 and x, as the destination base a = x; while (x >= y) { t = 1; for (i = 0; x > y; i++) { x /= y; } cout << x; for (j = 0; j < i; j++) { t *= y; } a = a - (t*x); x = a; } cout << x<<endl; c++


2 Answers

This is a job for struct:

>>> s = 'YZ'
>>> struct.unpack('>Q', '\x00' * (8 - len(s)) + s)
(22874,)

Or a bit trickier:

>>> int(s.encode('hex'), 16)
22874
like image 125
Roman Bodnarchuk Avatar answered Sep 25 '22 22:09

Roman Bodnarchuk


I don't think there's a built-in method to do this, but it's easy enough to cook up:

>>> int("".join([hex(ord(x))[2:] for x in "YZ"]), 16)
22874

This goes via base 16 which can of course be optimized out. I'll leave that "as an exercise".

like image 27
unwind Avatar answered Sep 22 '22 22:09

unwind