octet string conversion
Bengt Richter
bokr at oz.net
Mon Jul 28 23:31:05 EDT 2003
On 28 Jul 2003 13:14:50 -0700, ruach at chpc.utah.edu (Matthew) wrote:
>I am working on some software that uses SNMP to get information from
>routers and switches. I am using the pysnmp module (v2.0.8) to do the
>snmp part. The problem that I am having is that when I query a router
>for mac addresses pysnmp returns octetstrings like this:
>
>\000\002\263\254\264\351
>\010\000 \301F\021
>\010\000 \300\303[
>\000\002\263\254\264\241
>
>what I need though is hex strings like this:
>
>0:e0:7d:de:5:48
>0:e0:7d:c8:dc:9f
>8:0:36:4:3b:de
>0:80:ad:3a:9e:2b
>
>Can anyone tell me how to convert the octet strings to hex strings?
>
Assuming that your data is really octal character representations like \nnn,
and the spaces, F, and [ in the middle lines are typos, and that your need example
has nothing to do with the example data,
>>> data = r"""
... \000\002\263\254\264\351
... \010\000\301\021
... \010\000\300\303
... \000\002\263\254\264\241
... """
>>> for line in data.splitlines():
... if not line: continue # skip the first \n in data above
... print 'line: %r' %line
... oct3list = line.split('\\')[1:]
... print 'oct3list: %r'%oct3list
... octvals = [int(oct3,8) for oct3 in oct3list]
... print 'octvals: %r'%octvals
... hexstrings = ['%02X'%octval for octval in octvals]
... print 'hexstrings: %r'%hexstrings
... print 'joined with colons => %r' % ':'.join(hexstrings)
... print
...
line: '\\000\\002\\263\\254\\264\\351'
oct3list: ['000', '002', '263', '254', '264', '351']
octvals: [0, 2, 179, 172, 180, 233]
hexstrings: ['00', '02', 'B3', 'AC', 'B4', 'E9']
joined with colons => '00:02:B3:AC:B4:E9'
line: '\\010\\000\\301\\021'
oct3list: ['010', '000', '301', '021']
octvals: [8, 0, 193, 17]
hexstrings: ['08', '00', 'C1', '11']
joined with colons => '08:00:C1:11'
line: '\\010\\000\\300\\303'
oct3list: ['010', '000', '300', '303']
octvals: [8, 0, 192, 195]
hexstrings: ['08', '00', 'C0', 'C3']
joined with colons => '08:00:C0:C3'
line: '\\000\\002\\263\\254\\264\\241'
oct3list: ['000', '002', '263', '254', '264', '241']
octvals: [0, 2, 179, 172, 180, 161]
hexstrings: ['00', '02', 'B3', 'AC', 'B4', 'A1']
joined with colons => '00:02:B3:AC:B4:A1'
and I got it wrong because I used fixed 2-char hex in upper case,
and I'm showing the repr() of the line, which doubles the \'s,
then you can fix it ;-)
And get this for the data:
line: \000\002\263\254\264\351
joined with colons => '0:2:b3:ac:b4:e9'
line: \010\000\301\021
joined with colons => '8:0:c1:11'
line: \010\000\300\303
joined with colons => '8:0:c0:c3'
line: \000\002\263\254\264\241
joined with colons => '0:2:b3:ac:b4:a1'
In future, please post actual data and corresponding output
(or if you did this time, explain the anomalies). Otherwise
it's a guessing game, and wastes all of our time except for
silly finger exercises.
Regards,
Bengt Richter
More information about the Python-list
mailing list