473,748 Members | 4,804 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

hex(-5) => Futurewarning: ugh, can't we have a better hex than '-'[:n<0]+hex(abs(n)) ??

>>> hex(-5)
__main__:1: FutureWarning: hex()/oct() of negative int will return a signed string in Python 2.4
and up
'0xfffffffb'
hex(-5) '0xfffffffb' hex(-5L)

'-0x5L'

That is sooo ugly. I suppose it is for a backwards compatible repr, but couldn't we
at least have hex(n, newformat=False ) so that we can do

hex(-5, True) => 1xb # 1x signals an arbitrary number of prefixed f's
hex( 5, True) => 0x5

and have int() and long() recognize these?

Also would need a variant of %x and %X for formatting with the % operator.

Regards,
Bengt Richter
Jul 18 '05 #1
6 2140

"Bengt Richter" <bo**@oz.net> schrieb im Newsbeitrag
news:bh******** **@216.39.172.1 22...
hex(-5)

__main__:1: FutureWarning: hex()/oct() of negative int will return a

signed string in Python 2.4 and up '0xfffffffb'

[...]

There is a thread from this morning ("bitwise not ...") - this should be an
excellent contribution!
I have no mercy with someone writing hex(-5)

Kindly
Michael P
Jul 18 '05 #2
"Michael Peuser" <mp*****@web.de > wrote in news:bh******** *****@news.t-
online.com:

"Bengt Richter" <bo**@oz.net> schrieb im Newsbeitrag
news:bh******** **@216.39.172.1 22...
>>> hex(-5)

__main__:1: FutureWarning: hex()/oct() of negative int will return a

signed string in Python 2.4 and up '0xfffffffb'

[...]

There is a thread from this morning ("bitwise not ...") - this should be an
excellent contribution!
I have no mercy with someone writing hex(-5)

Kindly
Michael P


What about crazy people like myself? If you generate a crc32 value with zib,
you occasionally get a negative number returned. If you try to convert that
to hex (to test against a stored CRC32 value), it spits out a FutureWarning
at me. So you end up with silly things like this in your code:
# Disable FutureWarning, since it whinges about us making bad hex values :(
import warnings
try:
warnings.filter warnings(action ='ignore', category=Future Warning)
except NameError:
del warnings
--
Remove the oinks!
Jul 18 '05 #3
Freddie <oi*********@oi nkshlick.oinkne t> writes:
There is a thread from this morning ("bitwise not ...") - this should be an
excellent contribution!
I have no mercy with someone writing hex(-5)

Kindly
Michael P


What about crazy people like myself? If you generate a crc32 value with zib,
you occasionally get a negative number returned. If you try to convert that
to hex (to test against a stored CRC32 value), it spits out a FutureWarning
at me.


Read the thread about bitwise not. Tell Python how many bits you
want. In case of CRC32 that is of course 32 bits:
hex(-5&2**32-1)

Two questions: What is the best way to generate bitmask of n bits all
ones? And would sombody explain why hexadecimal (and octal) literals
behave differently from decimal literals? (see:
http://www.python.org/doc/current/ref/integers.html ) Why hexadecimal
literals from 0x80000000 to 0xffffffff are interpetred as negative
numbers instead of converting to long integers?

--
Juha Autero
http://www.iki.fi/jautero/
Eschew obscurity!
Jul 18 '05 #4
On Mon, Aug 18, 2003 at 07:56:42AM +0300, Juha Autero wrote:
Two questions: What is the best way to generate bitmask of n bits all
ones?


def ones(n):
r = (1l << n) - 1
try:
r = int(r)
except OverflowError:
pass
return r

does this do what you want? It gives these results:

# 2.3b1 (old, but should have 2.3's long vs int quirks)
for i in (0, 1, 2, 3, 31, 32, 33, 63, 64, 65): .... print "%2s %22s %22s" % (i, `ones(i)`, hex(ones(i)))
....
0 0 0x0
1 1 0x1
2 3 0x3
3 7 0x7
31 2147483647 0x7fffffff
32 4294967295L 0xFFFFFFFFL
33 8589934591L 0x1FFFFFFFFL
63 922337203685477 5807L 0x7FFFFFFFFFFFF FFFL
64 184467440737095 51615L 0xFFFFFFFFFFFFF FFFL
65 368934881474191 03231L 0x1FFFFFFFFFFFF FFFFL

# 2.2.2 for i in (0, 1, 2, 3, 31, 32, 33, 63, 64, 65):

.... print "%2s %22s %22s" % (i, `ones(i)`, hex(ones(i)))
....
0 0 0x0
1 1 0x1
2 3 0x3
3 7 0x7
31 2147483647 0x7fffffff
32 4294967295L 0xFFFFFFFFL
33 8589934591L 0x1FFFFFFFFL
63 922337203685477 5807L 0x7FFFFFFFFFFFF FFFL
64 184467440737095 51615L 0xFFFFFFFFFFFFF FFFL
65 368934881474191 03231L 0x1FFFFFFFFFFFF FFFFL
Jul 18 '05 #5
On Mon, 18 Aug 2003 09:16:48 +0200, "Michael Peuser" <mp*****@web.de > wrote:

"Juha Autero" <Ju*********@ik i.fi> schrieb im Newsbeitrag
news:ma******* *************** ************@py thon.org...
Freddie <oi*********@oi nkshlick.oinkne t> writes:
>> There is a thread from this morning ("bitwise not ...") - this shouldbe an >> excellent contribution!
>> I have no mercy with someone writing hex(-5)
>>
>> Kindly
>> Michael P
>>
>>
>
> What about crazy people like myself? If you generate a crc32 value withzib, > you occasionally get a negative number returned. If you try to convertthat > to hex (to test against a stored CRC32 value), it spits out aFutureWarnin g > at me.


Read the thread about bitwise not. Tell Python how many bits you
want. In case of CRC32 that is of course 32 bits:
hex(-5&2**32-1)

Two questions: What is the best way to generate bitmask of n bits all
ones?


Why do you object to 2**n-1? This is just fine I think.
And would sombody explain why hexadecimal (and octal) literals
behave differently from decimal literals? (see:
http://www.python.org/doc/current/ref/integers.html ) Why hexadecimal
literals from 0x80000000 to 0xffffffff are interpetred as negative
numbers instead of converting to long integers?


Most of all this has practical reasons because of the use most programmers
have for stating hexadecimal literals.

Of couse some hex literals are not interpreted as negative numbers but the
memory contents, because it has become undistinguishab le what the origin had
been.

One will not expect
print int(0xffffffff )
do something different from
x=0xffffffff
print int(x)

Unfortunately, the path to unification of integers to hardware-width independence
has backwards compatibility problems. I guess they are worse than for true division,
but has anyone really attempted to get a measure of them?

The options for hex representation seem to be (in terms of regexes)

1) signed standard: [+-]?0x[0-9a-fA-F]+
2) unprefixed standard: [0-9a-fA-F]+
which are produced by hex() and '%x' and '%X'
and interpreted by int(x, 16)

There is a need for a round trip hex representation/interpretation for signed integers
of arbitrary size, but IMO a prefixed '-' does violence to the usual expectation
for hex representation (i.e., a sensible view of the bits involved in a conventional
"two's complement" representation of the number to whatever width required).

I hope it can be avoided as a default, but that at a minimum, that an alternative will be provided.

For hex literals, the [01]x[0-9a-fA-F]+ variation seems clean (I forgot again who came up with that as
the best emerging alternative in an old thread, but credit is due). Tim liked it too, I believe ;-)

Since hex() will change anyway, how much more breakage will hex(-1) => 1xf create vs => -0x1 ?
Not to harp, but obviously the -0x1 gives no sense of the conventional underlying bit pattern
of ...fffff. (I am talking about an abstract bit pattern that extends infinitely to the left,
not a concrete implementation. Of course it is often useful to know how the abstraction gets
implemented on a particular platform, but that is not the only use for hex. It is also handy
as a human-readable representatatio n of an abstract bit sequence).

The other question is what to do with '%x'. The current 2.3 version doesn't seem to pay much
attention to field widths other than as a minimum, so that may offer an opportunity to control
the output. It does not generate an '0x' prefix ( easy for the positive case to specify as
0x%x) yet negatives presumably will prefix a '-'. (Will 0x-abcd be legal??)
What are some other possibilities?

Looking forward to using widths, what would one hope to get from '%2.2x'%-1 ?
I would hope for 'ff', personally ;-) And ' 1' for '%2.2x'%1 and '01' for %02.2x'%1.

Coming at it from this end, what happens if we drop the max width? What should we get
for '%02x'%1 ? That's easy: '01' as now. But '%02x'%-1 => 'ffffffff' currently, and that has
to change. Apparently to '-1' if things go as they're going? (Again, hexness is lost).

A possibility for unrestricted output width would be to print enough hex characters for an
unambiguous interpretation of sign. I.e., so that there are enough bits to include the sign
and an optional number of copies to pad to a full 4-bit hex character as necessary. This would
mean '%02x'%-1 => ff since that gives the first hex character the right sign.

That has the wrong interpretation (if you want to recover the signed value) for
int(('%02x'%-1),16) so that would need a fix for easy use. Although I usually dislike passing
flag info to functions by negating nonzero parameters, it would have mnemonic value in this case.
E.g., int(('%02x'%-1), -16) or the equivalent int('ff', -16) could mean use the leading bit as sign.
This convention would translate nicely to octal and binary string representations as well.

Of course int(('%02x'%255 ) could not return 'ff' as an unconstrained-width representation. It
would have to be '0ff' to provide the proper sign. Note that constraining this to a max width
of 2 would give 'ff'. This works for octal and binary too.

IMO this way of avoiding '-' in hex, octal, and binary string formats would make the strings
represent the data more clearly. These formats are mainly to communicate bit patterns IMO,
not just alternative ways to spell integer values.

If we have 1xf as a literal for spelling -0x1, I guess we don't need a literal format
for the leading-bit-as-sign convention. But the latter would be a way of reading and writing
signed arbitrary-width hex without losing the hexness of n the way you would with

'%c%x'%('-'[:n<0],abs(n)) #yech, gak ;-/

Regards,
Bengt Richter
Jul 18 '05 #6
"Michael Peuser" <mp*****@web.de > writes:
Two questions: What is the best way to generate bitmask of n bits all
ones?


Why do you object to 2**n-1? This is just fine I think.


Maybe I should have said "What other ways there are to generate a
bitmask of n bits all ones?" 2**n-1 seemed like a hack since it relies
on certain properties of binary numbers, but on the other hand all
bitmask processing relies on certain properties of binary numbers.

--
Juha Autero
http://www.iki.fi/jautero/
Eschew obscurity!
Jul 18 '05 #7

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

Similar topics

122
4288
by: ivan | last post by:
hi all, if I have: if(A && B || C) which operation gets executed first? If I remeber well should be &&, am I correct? thanks
1
2109
by: Leeor Chernov | last post by:
Hi , I need an article(Page URL) that shows that child elements on the same level cant have the same name(Validation is illegal...).... for example : <Parent> <item/> <item/> <item/> </Parent>
0
8991
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
9544
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
9324
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
9247
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
8243
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6074
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
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3313
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
2783
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.