From cc19b09b376163dcf310ed0d170a84c3e04e6556 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 19 Nov 2018 22:48:52 +0100 Subject: [PATCH] Bytes and Struct --- README.md | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 9319ee1..7863cf3 100644 --- a/README.md +++ b/README.md @@ -637,13 +637,20 @@ raise IOError("input/output error") Bytes ----- -**Bytes objects are immutable sequences of single bytes.** +**Bytes objects are immutable sequences of single bytes:** ```python +# str = b'' + = .decode('utf-8') + +# int = .to_bytes(, byteorder='big|small', signed=False) - = bytes.fromhex() = int.from_bytes(, byteorder='big|small', signed=False) + +# hex + = bytes.fromhex() = .hex() + = b''.join() ``` @@ -656,34 +663,34 @@ def read_bytes(filename): Struct ------ -**Conversions between Python values and C structs represented as Python bytes objects.** +**This module performs conversions between Python values and C structs represented as Python bytes objects:** ```python - = struct.pack(, [, , ...]) - = struct.unpack(, ) + = struct.pack('', [, , ...]) + = struct.unpack('', ) +``` + +### Example +```python +>>> from struct import pack, unpack, calcsize +>>> pack('hhl', 1, 2, 3) +b'\x00\x01\x00\x02\x00\x00\x00\x03' +>>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') +(1, 2, 3) +>>> calcsize('hhl') +8 ``` ### Format **Use capital leters for unsigned type.** -* `x` - Pad byte +* `x` - pad byte * `c` - char * `h` - short * `i` - int * `l` - long -* `l` - long * `q` - long long * `f` - float * `d` - double -### Example -```python ->>> from struct import * ->>> pack('hhl', 1, 2, 3) -b'\x00\x01\x00\x02\x00\x00\x00\x03' ->>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') -(1, 2, 3) ->>> calcsize('hhl') -8 -``` Threading ---------