Muhammad Ali Qadri
Muhammad Ali Qadri

Reputation: 626

Convert Hexadecimal string to long python

I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value

here is my code in python:

v = 99997
ttm = pack('>i', v) # change the integer to big endian form 
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r

Output: %x set(['\x00\x01\x86\x9d'])

Error: invalid literal for long() with base 16: '\x00\x01\x86\x9d'

As the string is already in hex form why isn't it converting to a long? How would I remove this error and what is the solution to this problem.

Upvotes: 1

Views: 3541

Answers (4)

Radu Diță
Radu Diță

Reputation: 14191

pack will return a string representation of the data you provide.

The string representation is different than a base 16 of a long number. Notice the \x before each number.

Edit:

try this

ttm = pack('>I',v)
final, = unpack('<I',ttm)
print ttm

Notice the use of I, this so the number is treated as an unsigned value

Upvotes: 1

Israel Unterman
Israel Unterman

Reputation: 13510

This is a nice question.

Here is what you are looking for.

s = str(ttm)
for ch in r"\bx'":
    s = s.replace(ch, '')

print(int(s, 16))

The problem is that ttm is similar to a string in some aspects. This is what is looks like: b'\x00\x01\x86\x9d'. Supplying it to int (or long) keeps all the non-hex characters. I removed them and then it worked.

After removing the non-hex-digit chars, you are left with 0001869d which is indeed 99997

Comment I tried it on Python 3. But on Python 2 it will be almost the same, you won't have the b attached to the string, but otherwise it's the same thing.

Upvotes: 0

uphill
uphill

Reputation: 409

You have to use struct.unpack as a reverse operation to struct.pack.

r, = unpack('<i', ttm)

this will r set to -1652162304.

Upvotes: 1

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140276

You just converted the integer value to big endian binary bytes.

This is useful mostly to embed in messages addressed to big-endian machines (PowerPC, M68K,...)

Converting to long like this means parsing the ttm string which should be 0x1869D as ASCII. (and the print statement does not work either BTW)

If I just follow your question title: "Convert hexadecimal string to long":

just use long("0x1869D",16). No need to serialize it. (BTW long only works in python 2. In python 3, you would have to use int since all numbers are represented in the long form)

Well, I'm answering to explain why it's bound to fail, but I'll edit my answer when I really know what you want to do.

Upvotes: 0

Related Questions