Python from bytes to binary

struct — Interpret bytes as packed binary data¶

This module converts between Python values and C structs represented as Python bytes objects. Compact format strings describe the intended conversions to/from Python values. The module’s functions and objects can be used for two largely distinct applications, data exchange with external sources (files or network connections), or data transfer between the Python application and the C layer.

When no prefix character is given, native mode is the default. It packs or unpacks data based on the platform and compiler on which the Python interpreter was built. The result of packing a given C struct includes pad bytes which maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. In contrast, when communicating data between external sources, the programmer is responsible for defining byte ordering and padding between elements. See Byte Order, Size, and Alignment for details.

Several struct functions (and methods of Struct ) take a buffer argument. This refers to objects that implement the Buffer Protocol and provide either a readable or read-writable buffer. The most common types used for that purpose are bytes and bytearray , but many other types that can be viewed as an array of bytes implement the buffer protocol, so that they can be read/filled without additional copying from a bytes object.

Functions and Exceptions¶

The module defines the following exception and functions:

Exception raised on various occasions; argument is a string describing what is wrong.

Return a bytes object containing the values v1, v2, … packed according to the format string format. The arguments must match the values required by the format exactly.

Pack the values v1, v2, … according to the format string format and write the packed bytes into the writable buffer buffer starting at position offset. Note that offset is a required argument.

struct. unpack ( format , buffer ) ¶

Unpack from the buffer buffer (presumably packed by pack(format, . ) ) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize() .

struct. unpack_from ( format , / , buffer , offset = 0 ) ¶

Unpack from buffer starting at position offset, according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes, starting at position offset, must be at least the size required by the format, as reflected by calcsize() .

Читайте также:  How to comment in javascript

struct. iter_unpack ( format , buffer ) ¶

Iteratively unpack from the buffer buffer according to the format string format. This function returns an iterator which will read equally sized chunks from the buffer until all its contents have been consumed. The buffer’s size in bytes must be a multiple of the size required by the format, as reflected by calcsize() .

Each iteration yields a tuple as specified by the format string.

Return the size of the struct (and hence of the bytes object produced by pack(format, . ) ) corresponding to the format string format.

Format Strings¶

Format strings describe the data layout when packing and unpacking data. They are built up from format characters , which specify the type of data being packed/unpacked. In addition, special characters control the byte order, size and alignment . Each format string consists of an optional prefix character which describes the overall properties of the data and one or more format characters which describe the actual data values and padding.

Byte Order, Size, and Alignment¶

By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). This behavior is chosen so that the bytes of a packed struct correspond exactly to the memory layout of the corresponding C struct. Whether to use native byte ordering and padding or standard formats depends on the application.

Alternatively, the first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table:

Источник

binascii — Convert between binary and ASCII¶

The binascii module contains a number of methods to convert between binary and various ASCII-encoded binary representations. Normally, you will not use these functions directly but use wrapper modules like uu or base64 instead. The binascii module contains low-level functions written in C for greater speed that are used by the higher-level modules.

a2b_* functions accept Unicode strings containing only ASCII characters. Other functions only accept bytes-like objects (such as bytes , bytearray and other objects that support the buffer protocol).

Changed in version 3.3: ASCII-only unicode strings are now accepted by the a2b_* functions.

Читайте также:  Спецсимволы в html примеры

The binascii module defines the following functions:

Convert a single line of uuencoded data back to binary and return the binary data. Lines normally contain 45 (binary) bytes, except for the last line. Line data may be followed by whitespace.

binascii. b2a_uu ( data , * , backtick = False ) ¶

Convert binary data to a line of ASCII characters, the return value is the converted line, including a newline char. The length of data should be at most 45. If backtick is true, zeros are represented by ‘`’ instead of spaces.

Changed in version 3.7: Added the backtick parameter.

Convert a block of base64 data back to binary and return the binary data. More than one line may be passed at a time.

If strict_mode is true, only valid base64 data will be converted. Invalid base64 data will raise binascii.Error .

  • Conforms to RFC 3548.
  • Contains only characters from the base64 alphabet.
  • Contains no excess data after padding (including excess padding, newlines, etc.).
  • Does not start with a padding.

Changed in version 3.11: Added the strict_mode parameter.

Convert binary data to a line of ASCII characters in base64 coding. The return value is the converted line, including a newline char if newline is true. The output of this function conforms to RFC 3548.

Changed in version 3.6: Added the newline parameter.

Convert a block of quoted-printable data back to binary and return the binary data. More than one line may be passed at a time. If the optional argument header is present and true, underscores will be decoded as spaces.

binascii. b2a_qp ( data , quotetabs = False , istext = True , header = False ) ¶

Convert binary data to a line(s) of ASCII characters in quoted-printable encoding. The return value is the converted line(s). If the optional argument quotetabs is present and true, all tabs and spaces will be encoded. If the optional argument istext is present and true, newlines are not encoded but trailing whitespace will be encoded. If the optional argument header is present and true, spaces will be encoded as underscores per RFC 1522. If the optional argument header is present and false, newline characters will be encoded as well; otherwise linefeed conversion might corrupt the binary data stream.

binascii. crc_hqx ( data , value ) ¶

Compute a 16-bit CRC value of data, starting with value as the initial CRC, and return the result. This uses the CRC-CCITT polynomial x 16 + x 12 + x 5 + 1, often represented as 0x1021. This CRC is used in the binhex4 format.

Читайте также:  PHP Form

binascii. crc32 ( data [ , value ] ) ¶

Compute CRC-32, the unsigned 32-bit checksum of data, starting with an initial CRC of value. The default initial CRC is zero. The algorithm is consistent with the ZIP file checksum. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows:

print(binascii.crc32(b"hello world")) # Or, in two pieces: crc = binascii.crc32(b"hello") crc = binascii.crc32(b" world", crc) print('crc32 = '.format(crc)) 

Changed in version 3.0: The result is always unsigned.

binascii. b2a_hex ( data [ , sep [ , bytes_per_sep=1 ] ] ) ¶ binascii. hexlify ( data [ , sep [ , bytes_per_sep=1 ] ] ) ¶

Return the hexadecimal representation of the binary data. Every byte of data is converted into the corresponding 2-digit hex representation. The returned bytes object is therefore twice as long as the length of data.

Similar functionality (but returning a text string) is also conveniently accessible using the bytes.hex() method.

If sep is specified, it must be a single character str or bytes object. It will be inserted in the output after every bytes_per_sep input bytes. Separator placement is counted from the right end of the output by default, if you wish to count from the left, supply a negative bytes_per_sep value.

>>> import binascii >>> binascii.b2a_hex(b'\xb9\x01\xef') b'b901ef' >>> binascii.hexlify(b'\xb9\x01\xef', '-') b'b9-01-ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b'_', 2) b'b9_01ef' >>> binascii.b2a_hex(b'\xb9\x01\xef', b' ', -2) b'b901 ef' 

Changed in version 3.8: The sep and bytes_per_sep parameters were added.

Return the binary data represented by the hexadecimal string hexstr. This function is the inverse of b2a_hex() . hexstr must contain an even number of hexadecimal digits (which can be upper or lower case), otherwise an Error exception is raised.

Similar functionality (accepting only text string arguments, but more liberal towards whitespace) is also accessible using the bytes.fromhex() class method.

Exception raised on errors. These are usually programming errors.

exception binascii. Incomplete ¶

Exception raised on incomplete data. These are usually not programming errors, but may be handled by reading a little more data and trying again.

Support for RFC compliant base64-style encoding in base 16, 32, 64, and 85.

Support for UU encoding used on Unix.

Support for quoted-printable encoding used in MIME email messages.

Источник

Оцените статью