How to convert a number to hex number?
Bengt Richter
bokr at oz.net
Wed Nov 9 00:22:35 EST 2005
On Wed, 09 Nov 2005 00:42:45 GMT, Ron Adam <rrr at ronadam.com> wrote:
>
>
>Bengt Richter wrote:
>> On 08 Nov 2005 08:07:34 -0800, Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
>>
>>
>>>"dcrespo" <dcrespo at gmail.com> writes:
>>>
>>>>>>>hex(255)[2:]
>>>>
>>>>'ff'
>>>
>>>'%x'%255 is preferable since the format of hex() output can vary. Try hex(33**33).
>>
>>
>> Not to mention (#@%*!-pletive deleted ;-)
>>
>> >>> hex(-255)[2:]
>> 'xff'
>> >>> hex(-255)
>> '-0xff'
>> >>> hex(-255&0xff)
>> '0x1'
>>
>> Regards,
>> Bengt Richter
>
>I just happen to have been playing around with converting bases the last
>couple of days. (idonowhy) ;-)
>
It seems to be one of those inevitable things, enjoy it ;-)
But you still use '-' + yourconversion(abs(x)) to deal with a negative number.
That's what I was #@%*!-ing about. You can't see the 'bits' in the way one was
used to with the old int values. My answer was a base-complement representation,
of which base-16 is a particular case. See
http://groups.google.com/group/comp.lang.python/msg/d8324946fcdff8f8
and the code in the second reference from there:
http://groups.google.co.uk/group/comp.lang.python/msg/359927a23eb15b3e
I only put in characters for up to base 36, but it's a function parameter
you can pass, so your digits ought to work if passed.
The idea of base-complement is that the first digit is the zero digit for
positive numbers and the digit for base-1 for negative numbers. This can
be arbitrarily repeated to the left as fill without changing the numeric value.
so for base 10 one is 01 and -1 is 99, and for hex that
is 01 and FF. For base 2, 01 and 11. Etc. To make a general
literal you need a prefix to the data that tells you the base value
to use in interpreting the data part. A la 0x01, I proposed
0b<base value in decimal>.<data part>
So +1 -1 is 0b2.01 and 0b2.11 or octal 0b8.01 and 0b8.77 or
decimal 0b10.01 and 0b10.99 and hex 0b16.01 and 0b16.ff
Algorithmically, minus 1 can be represented with a single data digit,
but that's a style issue.
>Oh yeah, I was thinking of using base62 to generate non-repeating id
>strings and wanted to try it out.
Hm, what were you going to use those for?
[...too tired to revisit the problem, just wanted to comment on the
sign/magnitude representation, hope I didn't typo too badly above ;-) ...]
Regards,
Bengt Richter
More information about the Python-list
mailing list