Example #1
0
def Flag(name, truth=1, falsehood=0, default=False):
    """
    A flag.

    Flags are usually used to signify a Boolean value, and this construct
    maps values onto the ``bool`` type.

    .. note:: This construct works with both bit and byte contexts.

    .. warning:: Flags default to False, not True. This is different from the
        C and Python way of thinking about truth, and may be subject to change
        in the future.

    :param name: field name
    :param truth: value of truth (default 1)
    :param falsehood: value of falsehood (default 0)
    :param default: default value (default False)
    """

    return SymmetricMapping(
        Field(name, 1),
        {
            True: int2byte(truth),
            False: int2byte(falsehood)
        },
        default=default,
    )
Example #2
0
def hexundump(data, linesize):
    r"""
    Reverse of ``hexdump()``.
    """
    raw = []
    for line in data.split("\n"):
        line = line[line.find(" "):].lstrip()
        bytes = [int2byte(int(s, 16)) for s in line[:3 * linesize].split()]
        raw.extend(bytes)
    return b"".join(raw)
Example #3
0
def hexundump(data, linesize):
    r"""
    Reverse of ``hexdump()``.
    """
    raw = []
    for line in data.split("\n"):
        line = line[line.find(" "):].lstrip()
        bytes = [int2byte(int(s,16)) for s in line[:3*linesize].split()]
        raw.extend(bytes)
    return b"".join(raw)
Example #4
0
def hexundump(data, linesize):
    r"""
    Reverse of ``hexdump()``.
    """
    raw = []
    fmtlinesize = 7 + 3 * linesize + 3 + linesize
    for line in data.split("\n"):
        bytes = [
            int2byte(int(s, 16)) for s in line[7:7 + 3 * linesize].split()
        ]
        raw.extend(bytes)
    return b"".join(raw)
Example #5
0
def Flag(name, truth = 1, falsehood = 0, default = False):
    """
    A flag.

    Flags are usually used to signify a Boolean value, and this construct
    maps values onto the ``bool`` type.

    .. note:: This construct works with both bit and byte contexts.

    .. warning:: Flags default to False, not True. This is different from the
        C and Python way of thinking about truth, and may be subject to change
        in the future.

    :param str name: field name
    :param int truth: value of truth (default 1)
    :param int falsehood: value of falsehood (default 0)
    :param bool default: default value (default False)
    """

    return SymmetricMapping(Field(name, 1),
        {True : int2byte(truth), False : int2byte(falsehood)},
        default = default,
    )
Example #6
0
from construct.lib.py3compat import byte2int, int2byte, bytes2str

# Map an integer in the inclusive range 0-255 to its string byte representation
_printable = dict((i, ".") for i in range(256))
_printable.update((i, bytes2str(int2byte(i))) for i in range(32, 128))


def hexdump(data, linesize):
    """
    data is a bytes object. The returned result is a string.
    """
    prettylines = []
    if len(data) < 65536:
        fmt = "%%04X   %%-%ds   %%s"
    else:
        fmt = "%%08X   %%-%ds   %%s"
    fmt = fmt % (3 * linesize - 1, )
    for i in range(0, len(data), linesize):
        line = data[i:i + linesize]
        hextext = " ".join('%02x' % byte2int(b) for b in line)
        rawtext = "".join(_printable[byte2int(b)] for b in line)
        prettylines.append(fmt % (i, str(hextext), str(rawtext)))
    return prettylines


class HexString(bytes):
    """
    Represents bytes that will be hex-dumped to a string when its string
    representation is requested.
    """
    def __init__(self, data, linesize=16):
Example #7
0
    """
    i = 0
    l = len(bits)
    output = [b""] * ((l // bytesize) + 1)
    j = len(output) - 1
    while i < l:
        output[j] = bits[i:i + bytesize]
        i += bytesize
        j -= 1
    return b"".join(output)


_char_to_bin = [0] * 256
_bin_to_char = {}
for i in range(256):
    ch = int2byte(i)
    bin = int_to_bin(i, 8)
    # Populate with for both keys i and ch, to support Python 2 & 3
    _char_to_bin[i] = bin
    _bin_to_char[bin] = ch


def encode_bin(data):
    """ 
    Create a binary representation of the given b'' object. Assume 8-bit
    ASCII. Example:

        >>> encode_bin('ab')
        b"\x00\x01\x01\x00\x00\x00\x00\x01\x00\x01\x01\x00\x00\x00\x01\x00"
    """
    return six.b("").join(_char_to_bin[ord(ch)] for ch in data)
Example #8
0
from construct.lib.py3compat import byte2int, int2byte, bytes2str, iteratebytes, iterateints
from binascii import hexlify, unhexlify

# Map an integer in the inclusive range 0-255 to its string byte representation
_printable = [
    bytes2str(int2byte(i)) if 32 <= i < 128 else '.' for i in range(256)
]
_hexprint = [format(i, '02X') for i in range(256)]


def hexdump(data, linesize):
    r"""
    Turns bytes into a unicode string of the format:

    >>>print(hexdump(b'0' * 100, 16))
    0000   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0010   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0020   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0030   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0040   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0050   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0060   30 30 30 30                                       0000             
    """
    if len(data) < 16**4:
        fmt = "%%04X   %%-%ds   %%s" % (3 * linesize - 1, )
    elif len(data) < 16**8:
        fmt = "%%08X   %%-%ds   %%s" % (3 * linesize - 1, )
    else:
        raise ValueError(
            "hexdump cannot process more than 16**8 or 4294967296 bytes")
    prettylines = []
Example #9
0
        Logical opposite of int_to_bin. Both '0' and '\x00' are considered zero,
        and both '1' and '\x01' are considered one. Set sign to True to interpret
        the number as a 2-s complement signed integer.
        """
        bits = "".join("01"[b & 1] for b in bits)
        if signed and bits[0] == "1":
            bits = bits[1:]
            bias = 1 << len(bits)
        else:
            bias = 0
        return int(bits, 2) - bias

    _char_to_bin = [0] * 256
    _bin_to_char = {}
    for i in range(256):
        ch = int2byte(i)
        bin = int_to_bin(i, 8)
        # Populate with for both keys i and ch, to support Python 2 & 3
        _char_to_bin[i] = bin
        _bin_to_char[bin] = ord(ch)

    def encode_bin(data):
        """ 
        Create a binary representation of the given b'' object. Assume 8-bit
        ASCII. Example:
    
            >>> encode_bin('ab')
            b"\x00\x01\x01\x00\x00\x00\x00\x01\x00\x01\x01\x00\x00\x00\x01\x00"
        """
        return six.b("").join(_char_to_bin[int(ch)] for ch in data)
Example #10
0
from construct.lib.py3compat import byte2int, int2byte, bytes2str, iteratebytes, iterateints


# Map an integer in the inclusive range 0-255 to its string byte representation
_printable = [bytes2str(int2byte(i)) if 32 <= i < 128 else '.' for i in range(256)]
_hexprint = [format(i, '02X') for i in range(256)]

def hexdump(data, linesize):
    r"""
    Turns bytes into a unicode string of the format:

    >>>print(hexdump(b'0' * 100, 16))
    0000   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0010   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0020   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0030   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0040   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0050   30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30   0000000000000000
    0060   30 30 30 30                                       0000             
    """
    if len(data) < 16**4:
        fmt = "%%04X   %%-%ds   %%s" % (3 * linesize - 1,)
    elif len(data) < 16**8:
        fmt = "%%08X   %%-%ds   %%s" % (3 * linesize - 1,)
    else:
        raise ValueError("hexdump cannot process more than 16**8 or 4294967296 bytes")
    prettylines = []
    for i in range(0, len(data), linesize):
        line = data[i:i+linesize]
        hextext = " ".join(_hexprint[b] for b in iterateints(line))
        rawtext = "".join(_printable[b] for b in iterateints(line))
Example #11
0
from construct.lib.py3compat import byte2int, int2byte, bytes2str


# Map an integer in the inclusive range 0-255 to its string byte representation
_printable = dict((i, ".") for i in range(256))
_printable.update((i, bytes2str(int2byte(i))) for i in range(32, 128))


def hexdump(data, linesize):
    """
    data is a bytes object. The returned result is a string.
    """
    prettylines = []
    if len(data) < 65536:
        fmt = "%%04X   %%-%ds   %%s"
    else:
        fmt = "%%08X   %%-%ds   %%s"
    fmt = fmt % (3 * linesize - 1,)
    for i in range(0, len(data), linesize):
        line = data[i : i + linesize]
        hextext = " ".join("%02x" % byte2int(b) for b in line)
        rawtext = "".join(_printable[byte2int(b)] for b in line)
        prettylines.append(fmt % (i, str(hextext), str(rawtext)))
    return prettylines


try:
    basecls = bytes
except NameError:
    basecls = str