how to preserve hex value

B

Back9

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
 
M

member thudfoo

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
|109> '%02X' % 10
<109> '0A'
 
J

J. Cliff Dyer

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
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,807
Latest member
ryef

Latest Threads

Top