473,395 Members | 1,956 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

hex to signed integer

Hello,

My question basically is: What is the opposite of the following?
| "%08X" % -1

I want to convert a string of hexadecimal characters to the signed
integer they would have been before the <print> statement converted
them. How do I do this in such a way that is compatible with Python
versions 1.5.2 through 2.4, and not machine-dependent?

This is my current best:
| struct.unpack("!l", \
| chr(string.atoi(hexbit[0:2], 16)) + \
| chr(string.atoi(hexbit[2:4], 16)) + \
| chr(string.atoi(hexbit[4:6], 16)) + \
| chr(string.atoi(hexbit[6:8], 16)))

Thanks in advance.
--
Tom Goulet, to**@em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html
Jul 18 '05 #1
8 27061
Quoth Tom Goulet:
My question basically is: What is the opposite of the following?
| "%08X" % -1


Here's one way, very like what you already have:

def hex2signed(s):
return struct.unpack('!i', binascii.unhexlify(s))[0]

(This will not be the inverse of '%08x' % n in Python 2.4, when
'%x' % -1 will produce '-1', but I think it does what you want.)

Another approach:

def hex2signed(s):
value = long(s, 16)
if value > sys.maxint:
value = value - 2L*sys.maxint - 2
assert -sys.maxint-1 <= value <= sys.maxint
return int(value)

--
Steven Taschuk st******@telusplanet.net
"Please don't damage the horticulturalist."
-- _Little Shop of Horrors_ (1960)

Jul 18 '05 #2
Tom Goulet <to**@em.ca> wrote:
Hello,

My question basically is: What is the opposite of the following?
| "%08X" % -1

I want to convert a string of hexadecimal characters to the signed
integer they would have been before the <print> statement converted
them. How do I do this in such a way that is compatible with Python
versions 1.5.2 through 2.4, and not machine-dependent?

This is my current best:
| struct.unpack("!l", \
| chr(string.atoi(hexbit[0:2], 16)) + \
| chr(string.atoi(hexbit[2:4], 16)) + \
| chr(string.atoi(hexbit[4:6], 16)) + \
| chr(string.atoi(hexbit[6:8], 16)))


(Unrelated note: the blackslashes are unnecessary in this example, since it
is inside a set of parens.)

How slimy is this?

try:
temp = int(hexbit,16)
except:
temp = int(long(hexbit,16)-2**32)

Equivalently:
if hexbit[0] < '8':
temp = int(hexbit,16)
else:
temp = int(long(hexbit,16)-2**32)
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Jul 18 '05 #3
Steven Taschuk wrote:
return struct.unpack('!i', binascii.unhexlify(s))[0]
Hmm, <unhexlify> is not in <binascii> in Python 1.5.2.
(This will not be the inverse of '%08x' % n in Python 2.4, when
'%x' % -1 will produce '-1', but I think it does what you want.)
| >>> print "%08X" % -1294044542
| __main__:1: FutureWarning: %u/%o/%x/%X of negative int will return a \
| signed string in Python 2.4 and up

Argh. Thanks for warning me.

I only want to store thirty-two bits as an integer and input and output
that value of hexadecimal in Python versions 1.5.2 through 2.4, and it's
causing me a lot of grief. It looks like I'm going to have to resort to
<struct> for both input and output.
value = long(s, 16)


A second argument to <long> is not in Python 1.5.2, either. Using
<atol> from <string> instead works. Thanks!

--
Tom Goulet, to**@em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html
Jul 18 '05 #4
Hello Tom,
I want to convert a string of hexadecimal characters to the signed
integer they would have been before the <print> statement converted
them. How do I do this in such a way that is compatible with Python
versions 1.5.2 through 2.4, and not machine-dependent?

eval?
e.g.:
eval("0x%s" % "FF")

255

HTH.
Miki
Jul 18 '05 #5
Tim Roberts wrote:
Tom Goulet <to**@em.ca> wrote:
I want to convert a string of hexadecimal characters to the signed
integer they would have been before the <print> statement converted
them. How do I do this in such a way that is compatible with Python
versions 1.5.2 through 2.4, and not machine-dependent?

if hexbit[0] < '8':
temp = int(hexbit,16)
else:
temp = int(long(hexbit,16)-2**32)


The <int> function takes only one argument in Python 1.5.2.

--
Tom Goulet, to**@em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html
Jul 18 '05 #6
Miki Tebeka wrote:
eval?
e.g.:
eval("0x%s" % "FF")

255


| >>> eval("0x"+"B2DE7282", {}, {})
| <string>:0: FutureWarning: hex/oct constants > sys.maxint will return \
| positive values in Python 2.4 and up
| -1294044542

There you have it. Using the <eval> function doesn't work on 2.4 and
using the <int> function doesn't work on 1.5.2. Besides, I want to
avoid use of the <eval> function.

--
Tom Goulet, to**@em.ca, D8BAD3BC, http://web.em.ca/~tomg/contact.html
Jul 18 '05 #7
Tom Goulet <to**@em.ca> writes:
Tim Roberts wrote:
Tom Goulet <to**@em.ca> wrote:

I want to convert a string of hexadecimal characters to the signed
integer they would have been before the <print> statement converted
them. How do I do this in such a way that is compatible with Python
versions 1.5.2 through 2.4, and not machine-dependent?
if hexbit[0] < '8':
temp = int(hexbit,16)
else:
temp = int(long(hexbit,16)-2**32)


The <int> function takes only one argument in Python 1.5.2.


Yes, the base argument was added in later around Python 2.0.

An equivalent operation to int(value,base) in Python 1.5.2 and any of
the later versions (at least through 2.3 - 2.4 doesn't exist yet)
would be the string.atoi(value,base) function.

However, as indicated by the above code, both int() and string.atoi()
limit their result to a signed integer, so depending on the
hexadecimal string it might overflow and result in an exception. So
for any sized hexadecimal string, use string.atol(value,base) instead.

For example:

Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
import string
print string.atoi('20',16) 32 print string.atoi('FFFFFFFF',16) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "c:\Python\2.2\lib\string.py", line 225, in atoi
return _int(s, base)
ValueError: int() literal too large: FFFFFFFF print string.atol('FFFFFFFF',16) 4294967295 print string.atol('%08X' % -1,16) 4294967295


One note - if you end up converting the result of string.atol() with
str(), under Python 1.5.2 it will have a trailing "L" but will not
have that under any later Python release. Converting it to a string
with repr() will have the trailing "L" under all Python releases.

-- David
Jul 18 '05 #8
Quoth Bengt Richter:
[...]
>>> -2**31

-2147483648L
Oops, is that a wart/buglet BTW?


That it's a long and not an int? Certainly not a bug, arguably a
wart, and in any case it's 2's-complement's fault, not Python's:
-2**31 is equivalent to -(2**31), and the inner expression doesn't
fit into an int (on suitable machines).

I suppose long arithmetic could produce ints when possible, but it
seems unlikely to be worth the trouble.

--
Steven Taschuk "The world will end if you get this wrong."
st******@telusplanet.net -- "Typesetting Mathematics -- User's Guide",
Brian Kernighan and Lorrinda Cherry

Jul 18 '05 #9

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

Similar topics

19
by: MiniDisc_2k2 | last post by:
Okay, here's a question about the standard. What does it say about unsigned/signed mismatches in a comparison statement: char a = 3; unsigned char b = 255; if (a<b) Now what's the real...
8
by: Rade | last post by:
Following a discussion on another thread here... I have tried to understand what is actually standardized in C++ regarding the representing of integers (signed and unsigned) and their conversions....
2
by: Aire | last post by:
1. If a function defined as: void test_function(unsigned int a) { } Is "test_function(-256);" going to cause undefined behavior? 2. What's "a negative signed value wrapping"?
17
by: Christopher Dyken | last post by:
Hi group, I'm trying to implement two routines to handle 32x32-bits and 64x64-bits signed integer multiplication on a 32 bits machine in C. It easy to find descriptions of non-signed...
14
by: junky_fellow | last post by:
Can anybody please explain this: When a value with integer type is converted to another integer type other than _Bool, if the new type is unsigned, the value is converted by repeatedly...
27
by: REH | last post by:
I asked this on c.l.c++, but they suggested you folks may be better able to answer. Basically, I am trying to write code to detect overflows in signed integer math. I am trying to make it as...
11
by: Frederick Gotham | last post by:
I'd like to discuss the use of signed integers types where unsigned integers types would suffice. A common example would be: #include <cassert> #include <cstddef> int...
7
by: somenath | last post by:
Hi All, I am trying to undestand "Type Conversions" from K&R book.I am not able to understand the bellow mentioned text "Conversion rules are more complicated when unsigned operands are...
39
by: Juha Nieminen | last post by:
I was once taught that if some integral value can never have negative values, it's a good style to use an 'unsigned' type for that: It's informative, self-documenting, and you are not wasting half...
28
by: Fore | last post by:
Hello I am looking for some effecient way to convert a 32 bit unsigned integer to a 16 bit signed integer. All I want is the lower 16 bits of the 32 bit unsigned integer , with bit 15 (0..15) to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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
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
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...
0
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...

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.