From 59ba11488db12bb28543d12862d8746830da9077 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 19 Nov 2018 22:35:39 +0100 Subject: [PATCH] Bytes and Struct --- README.md | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8324e3c..9319ee1 100644 --- a/README.md +++ b/README.md @@ -344,7 +344,7 @@ Inline ### Lambda ```python lambda: -lambda , : +lambda , : ``` ### Comprehension @@ -414,7 +414,7 @@ multiply_by_3 = multiply_closure(3) #### Or: ```python from functools import partial -partial(, [, , ...]) +partial(, [, , ...]) ``` Decorator @@ -635,6 +635,56 @@ while True: raise IOError("input/output error") ``` +Bytes +----- +**Bytes objects are immutable sequences of single bytes.** +```python + = b'' + = .to_bytes(, byteorder='big|small', signed=False) + = bytes.fromhex() + = int.from_bytes(, byteorder='big|small', signed=False) + = .hex() + = b''.join() +``` + +### Read Bytes from file: +```python +def read_bytes(filename): + with open(filename, 'rb') as file: + return file.read() +``` + +Struct +------ +**Conversions between Python values and C structs represented as Python bytes objects.** +```python + = struct.pack(, [, , ...]) + = struct.unpack(, ) +``` + +### Format +**Use capital leters for unsigned type.** +* `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 --------- ```python @@ -1035,10 +1085,10 @@ def get_datetime_string(a_datetime): Audio ----- -#### Saves list of floats of size 0 to 1 to a WAV file: +#### Saves list of floats with values between 0 and 1 to a WAV file: ```python import wave, struct -frames = [struct.pack('%dh'%(1), int((a-0.5)*60000)) for a in ] +frames = [struct.pack('h', int((a-0.5)*60000)) for a in ] wf = wave.open(, 'wb') wf.setnchannels(1) wf.setsampwidth(4)