manipulating hex values
J. Cliff Dyer
jcd at unc.edu
Tue Apr 1 22:25:05 CEST 2008
On Tue, 2008-04-01 at 12:09 -0700, Stephen Cattaneo wrote:
> The source of my confusion is that I need to keep my bytes formated
> correctly. I am using the below 'raw socket example' proof-of-concept
> code as my example. (And yes, I have tried the proof-of-concept. It
> works correctly. It is not my code.)
> dstAddr = "\x01\x02\x03\x04\x05\x06"
> dstAddr1 = "0x010203040506"
> dstAddr != dstAddr1
> Follow up question: What is the best to store my bytes up until sending
> the packets? Perhaps I should use lists of decimal numbers and then
> before sending convert to hex.
> I.E. dstAddr = [ 1, 2, 3, 4, 5, 6]
> txFrame = struct.pack("!6s6sh",dstAddr,srcAddr,proto) + ethData
> Is there a better way to do this?
Those are not lists of decimal numbers. Those are lists of binary
numbers which are represented as decimal in the default conversion to
py>>> assert [10, 11, 12] == [0xa, 0xb, 0xc]
Don't worry about the formatting until you output them to strings. The
numbers are in there, and have the proper value, regardless of how you
input them. When you need to output them, you can use standard string
formatting to get the format you desire:
py>>> "%i is decimal" % a
'30 is decimal'
py>>> "%x is hexadecimal" % a
'1e is hexadecimal'
py>>> "0x%x is hex prepended with 0x" % a
'0x1e is hex prepended with 0x'
>>> "0%o is octal prepended with 0" % a
'036 is octal prepended with 0'
You are making your life more complicated than you need to.
More information about the Python-list