tags:

views:

21376

answers:

5

How do I convert a hex string to an int in Python? I may have it as "0xffff" or just "ffff".

+12  A: 

int(hexString, 16) does the trick, and works with and without the 0x prefix.

unwind
+5  A: 

For any given string s:

int(s, 16)
smink
+45  A: 

Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:

x = int("deadbeef", 16)

With the 0x prefix, Python can distinguish hex and decimal automatically:

>>> print int("0xdeadbeef", 0)
3735928559
>>> print int("10", 0)
10
Dan
A: 

Conversion from string to hexadecimal to integer

# Read 12 bit vectors as string from the text vectors file
self.ci = 0
self.idata = 0
self.qdata = 0
for self.ci in range(10, 11, 1):
   self.idata = self.rfile[self.ci] + self.rfile[self.ci+1] + self.rfile[self.ci+2]
   self.qdata = self.rfile[self.ci+5] + self.rfile[self.ci+6] + self.rfile[self.ci+7]    
   print self.idata, self.qdata

# Convert String to a Integer Value
self.idata_f = int(self.idata, 16)
self.qdata_f =  int(self.qdata, 16)
fullchip
A: 

How do you do the same as signed integer? It seems to be always unsigned:

int("0xFFFFFFFF", 16) 4294967295L

Bahadir Balban