hex(-5) => Futurewarning: ugh, can't we have a better hex than '-'[:n<0]+hex(abs(n)) ??
Jeff Epler
jepler at unpythonic.net
Mon Aug 18 12:14:33 EDT 2003
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 9223372036854775807L 0x7FFFFFFFFFFFFFFFL
64 18446744073709551615L 0xFFFFFFFFFFFFFFFFL
65 36893488147419103231L 0x1FFFFFFFFFFFFFFFFL
# 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 9223372036854775807L 0x7FFFFFFFFFFFFFFFL
64 18446744073709551615L 0xFFFFFFFFFFFFFFFFL
65 36893488147419103231L 0x1FFFFFFFFFFFFFFFFL
More information about the Python-list
mailing list