From: Back9 on
Hi,

When converting a hex value, I'd like to preserve the decimal
position.
For example, 0x0A is converted to 0A not just A in string.

How do I do this?

TIA
From: member thudfoo on
On Wed, May 19, 2010 at 11:38 AM, Back9 <backgoodoo(a)gmail.com> wrote:
> Hi,
>
> When converting a hex value, I'd like to preserve the decimal
> position.
> For example, 0x0A is converted to 0A not just A in string.
>
> How do I do this?
>
> TIA
> --
> http://mail.python.org/mailman/listinfo/python-list
>
|109> '%02X' % 10
<109> '0A'
From: J. Cliff Dyer on
On Wed, 2010-05-19 at 11:38 -0700, Back9 wrote:
> Hi,
>
> When converting a hex value, I'd like to preserve the decimal
> position.
> For example, 0x0A is converted to 0A not just A in string.
>
> How do I do this?
>
> TIA

I'm not sure I understand what your use case is, but generally speaking,
it is better to treat hex values as integers (which they are) than as
string (which they are not). 0x0a is an integer value of ten. There is
no change of decimal position gained by prepending a zero digit. It
means exactly the same thing. If you know how large a chunk is, you can
multiply (or bit-shift) and add to get the behavior you're looking for.

def concat(byte1, byte2):
return (byte1 << 8) + byte2

>>> hex(concat(0x43, 0x0a))
0x430a

One common use case is when using hex notation to represent sequences of
bytes. In this case, you may want to work with a byte string instead.
To concatenate your numbers this way, convert each number to a byte
using chr(x) (Python 2.x)

To print it as hex, do something like this:

def bytestring_to_hex(s):
return '0x + ''.join('%02x' % ord(x) for x in s)

However, if you need an arbitrary number of zeros preserved, you're out
of luck. They are semantically meaningless in python. (Is semantically
meaningless redundant?)

Cheers,
Cliff