Reputation: 59
How would I get the various outputs below to come out 0xFF or 0xFFFF?
>>> key=-1
>>> print(key)
-1
>>> print(hex(key))
-0x1
>>> print("Key={:4X}".format(key))
Key= -1
>>>
Upvotes: 1
Views: 52
Reputation: 8678
You could try something like that:
>>> def do_what_you_want(number, length):
... print(hex(number+(1<<(length*4))))
...
>>> do_what_you_want(-1, 2)
0xff
>>> do_what_you_want(-1, 4)
0xffff
Upvotes: 0
Reputation: 51989
Python integers are arbitrary precision – -1
cannot "wrap around" to the maximum value.
Explicitly wrap the number(s) to the desired range:
>>> key = -1
>>> hex(key % 256) # restrict to range 0-255
0xff
>>> hex(key % 65536) # restrict to range 0-65535
0xffff
Upvotes: 1