简体   繁体   中英

Hex string manipulation in Python

So I have a string of Hex values that typically goes like this:

'\x00\xff\xc0'

I need to take each bit (not byte, bit), and print it in an individual line of a table. For instance: if I have '\\xc0' I need to take the binary value 11000000 and print each individual 1 or 0 in a line. This works fine when functions return an 8 bit binary string, like \\xc0 returns 11000000 . But if I need a \\x00 to be converted to 8 zeros, then it doesn't work. To better clarify, I need to take a value like \\x01 and print it like this:

0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1

I tried using

bin(ord(value))

but had no success, for some values return binary strings with less than 8 bits. Does anyone know how it can be done?

Try this:

def byte2bin(byte_hex):
    return bin(int(byte_hex, 16))[2:].zfill(8)

Then you can do something like this:

hex = '\x00\xff\xc0'
str.join(' ', (byte2bin(h.encode('hex')) for h in hex))

Giving:

'00000000 11111111 11000000'

It is a bit unclear what you have tried and where the actual issue is. This should get you going, bintest.py , please make sure that you understand, step by step, what is happening in that script. You can ask in the comments if something remains unclear.

import sys


def bits(byte):
    """Convert byte (byte string of length 1) to bits (int of value,
    0 or 1), most significant bit first.
    """
    byte_as_int = ord(byte)
    for i in reversed(xrange(8)):
        yield (byte_as_int >> i) & 1


# Read byte string from first argument.
bytes = sys.argv[1]


# For each byte in the byte string, print all bit numbers and
# the corresponding bit value, in the format as asked.
for b in bytes:
    for i, bit in enumerate(bits(b)):
        print i, bit

Try it out:

$ python bintest.py $'\x01'
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 1

Notes: The $'...' is a neat syntax allowed by bash, it properly parses the \\xXX notation. The Python script only works for Python 2 (one of the most relevant point here is that Python 2 does not try to decode argv, argv is accessible in raw binary form). Also note that you cannot use \\x00 in the command line arguments, since it terminates the argument string (it terminates a C char array). You can, however, safely use \\x00 from within the Python script.

In python 3.x

>>> a='\x00\xff\xc0'
>>> ' '.join([bin(ord(x))[2:].zfill(8) for x in a])
'00000000 11111111 11000000'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM