473,666 Members | 2,281 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(0xdeadbe af) -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 9309
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(0xdeadbe af) -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******** *************** *************@p ython.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(0xdeadbe af) -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******* *************** **************@ 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(0xdeadbe af) -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,offs et=sys.maxint+1 ,modulus=(sys.m axint+1)*2):
"""short(n) converts a long into an int, ignoring high-order bits"""
return int(((what + offset) % modulus) - offset)

def poslong(what,mo dulus=(sys.maxi nt+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(0xdeadbee f)
print hexshort(short( 0xdeadbeef))
print long(hexshort(s hort(0xdeadbeef )),16)
print short(long(hexs hort(short(0xde adbeef)),16))

Hope this helps.

Pat
Jul 18 '05 #4
"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(0xdeadbe af) -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
5039
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 () { srand(time(0)); int array_length; int count;
7
3256
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 I couldn't find the exact rule in the C++ standard. And what if the classes have template parameters? It would be great if somebody could get me a rough hint where in the
2
2221
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 "Some errors happened during the conversion. No converted database was generated". This message is not of great assistance to me in sorting out the error!! I have not been able to find any helpful support on where to start looking
11
7606
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 Test. I expected the same error from the following line, but it compiles fine. The double is silently truncated to an int and then fed in to the implicit conversion operator. Why does this happen? Is there any way that I can keep the implicit...
2
1528
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 the conversion. I have trimmed my source down as much as possible. The classes implement something that behaves sort of like the Mediator design pattern, but where the colleagues are abstract, and can be added or removed on the fly. I guess...
6
2795
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
3131
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 utility in C++, before I forget everything. But it doesn't compile: ------------
11
2697
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> #include <string.h> #define LENGTH 20 int temp, m, n, i, r, base10, true;
3
7154
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
2630
by: Rahul | last post by:
Hi Everyone, I have the following code, class B; class A { public : operator B();
0
8443
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8356
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8866
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8550
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8639
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5663
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2769
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 we have to send another system
2
1772
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.