473,507 Members | 11,134 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Hex to int conversion error

When I try to convert an 8 digit hex number to an integer, I get a
ValueError. Why doesn't it convert back correctly? I have the string
'0xdeadbeaf' stored in a textbox and I would like it's integer value. I
would convert it to a long, but I need to pack it to send as a 4 byte
integer through a socket to a C program. Any ideas?
int(0xdeadbeaf) -559038801int(hex(int(0xdeadbeaf)) ,16)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: int() literal too large: 0xdeadbeaf

Nick

__________________________________________________ _______________
Enjoy MSN 8 patented spam control and more with MSN 8 Dial-up Internet
Service. Try it FREE for one month! http://join.msn.com/?page=dept/dialup
Jul 18 '05 #1
4 9305
Adam Ritter wrote:

When I try to convert an 8 digit hex number to an integer, I get a
ValueError. Why doesn't it convert back correctly? I have the string
'0xdeadbeaf' stored in a textbox and I would like it's integer value. I
would convert it to a long, but I need to pack it to send as a 4 byte
integer through a socket to a C program. Any ideas?
int(0xdeadbeaf) -559038801int(hex(int(0xdeadbeaf)) ,16)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: int() literal too large: 0xdeadbeaf


If your description above, that you "need to pack it to send as a
4 byte integer", is correct, you should need only the struct module:

struct.pack('L', long('deadbeef', 16))

The value 0xdeadbeef is negative if treated as an int (since ints are
signed in Python), so you can't treat it as an unsigned int. Instead,
since in effect you want to treat all values as unsigned, use long()
and the "L" (unsigned long) operand to struct.pack. Note that if you
then give it a negative long, you'll still get an OverflowError,
this time from struct.pack itself.

-Peter
Jul 18 '05 #2

"Adam Ritter" <te************@hotmail.com> wrote in message
news:ma************************************@python .org...
When I try to convert an 8 digit hex number to an integer, I get a
ValueError. Why doesn't it convert back correctly? I have the string
'0xdeadbeaf' stored in a textbox and I would like it's integer value. I
would convert it to a long, but I need to pack it to send as a 4 byte
integer through a socket to a C program. Any ideas?
int(0xdeadbeaf) -559038801int(hex(int(0xdeadbeaf)) ,16)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: int() literal too large: 0xdeadbeaf

Nick


Please see PEP 237. If the timeline in that PEP is still valid,
the meaning will change in Release 2.4.

John Roth
Jul 18 '05 #3
"Adam Ritter" <te************@hotmail.com> wrote in message news:<ma************************************@pytho n.org>...
When I try to convert an 8 digit hex number to an integer, I get a
ValueError. Why doesn't it convert back correctly? I have the string
'0xdeadbeaf' stored in a textbox and I would like it's integer value. I
would convert it to a long, but I need to pack it to send as a 4 byte
integer through a socket to a C program. Any ideas?
int(0xdeadbeaf) -559038801int(hex(int(0xdeadbeaf)) ,16)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: int() literal too large: 0xdeadbeaf


Unfortunately, that's what you get in 2.2, which is _different_
than what you'll get in 2.3, which is _still_ _different_ than
what you'll get in 2.4. This whole "deal with machine words"
is not really directly supported -- even using struct as
one previous poster suggested can lead to trouble.

The solution is to write your own 'hex' and 'int' functions.
The following code **should** work under 2.2, 2.3, and 2.4,
although it will give FutureWarnings under 2.3 (you can shut
them off using the filter in the warnings module).

import sys
def short(what,offset=sys.maxint+1,modulus=(sys.maxint +1)*2):
"""short(n) converts a long into an int, ignoring high-order bits"""
return int(((what + offset) % modulus) - offset)

def poslong(what,modulus=(sys.maxint+1)*2):
"""poslong(n) takes an int and returns a long with the same bit
pattern in the lower bits, and zeros in the upper bits. (Guaranteed
positive result)"""
return what % modulus

def hexshort(what):
"""hexshort(n) returns a hex number without any annoying minus sign in 2.4"""
return '0x%x' % poslong(what)

print short(0xdeadbeef)
print hexshort(short(0xdeadbeef))
print long(hexshort(short(0xdeadbeef)),16)
print short(long(hexshort(short(0xdeadbeef)),16))

Hope this helps.

Pat
Jul 18 '05 #4
"Adam Ritter" <te************@hotmail.com> wrote in message news:<ma************************************@pytho n.org>...
When I try to convert an 8 digit hex number to an integer, I get a
ValueError. Why doesn't it convert back correctly? I have the string
'0xdeadbeaf' stored in a textbox and I would like it's integer value. I
would convert it to a long, but I need to pack it to send as a 4 byte
integer through a socket to a C program. Any ideas?
int(0xdeadbeaf) -559038801int(hex(int(0xdeadbeaf)) ,16)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: int() literal too large: 0xdeadbeaf

In my previous post, I forgot to mention that the code sample
I gave only gives FutureWarnings because of the literal hex
constant used. In your real application, you will not need
to do this (because you will be using long(somestring,16),
similar to the third test line in my example). So the chances
are that you will not encounter any FutureWarnings using this
method.

Pat
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
4993
by: Tim Johansson | last post by:
I'm new to C++, and tried to start making a script that will shuffle an array. Can someone please tell me what's wrong? #include <iostream.h> #include <string.h> int main () {...
7
3249
by: Michael Lehn | last post by:
Hi, I have a question regarding the conversion of objects. When is the conversion done by the constructor and when by the operator. My feeling tells me that the constructor is preferred. But...
2
2209
by: Maurice | last post by:
Folks once again I look forward to your invaluable assistance. When converting an Access 2002 mdb back to Access 1997 using the Access 2002 inbuilt tools I receive the following error message...
11
7590
by: Steve Gough | last post by:
Could anyone please help me to understand what is happening here? The commented line produces an error, which is what I expected given that there is no conversion defined from type double to type...
2
1516
by: Harold Howe | last post by:
Howdy all, I am getting a compiler error regarding a consrained conversion. It complains that it can't make the type conversion, even though the generic type argument inherits from the target of...
6
2783
by: Dhirendra Singh | last post by:
Hi, The following C++ program is not compiling on my system. #include <iostream> using namespace std; class complex { double re, im; public: complex( ) :re(0), im(0) {}
31
3102
by: Martin Jørgensen | last post by:
Hi, I've had a introductory C++ course in the spring and haven't programmed in C++ for a couple of months now (but I have been programmed in C since january). So I decided to do my conversion...
11
2682
by: jyck91 | last post by:
// Base Conversion // Aim: This program is to convert an inputted number // from base M into base N. Display the converted // number in base N. #include <stdio.h> #include <stdlib.h>...
3
7139
by: fazulu deen | last post by:
Hi all, For the following code : file_ptr = fopen("pass_fail.txt", "a"); // error line 393 fdisplay(file_ptr, "Test Passed"); fclose(file_ptr);
6
2619
by: Rahul | last post by:
Hi Everyone, I have the following code, class B; class A { public : operator B();
0
7223
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7110
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7372
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7030
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
5041
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1540
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
758
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
411
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.