21 lines
651 B
Python
21 lines
651 B
Python
import pathlib
|
|
from typing import Union
|
|
|
|
import numpy as np
|
|
|
|
|
|
def file_to_bits(path: str | pathlib.Path) -> np.ndarray:
|
|
data = pathlib.Path(path).read_bytes()
|
|
bits = np.unpackbits(np.frombuffer(data, dtype=np.uint8))
|
|
return bits.astype(np.uint8) # shape (N,)
|
|
|
|
|
|
def bits_to_file(bits: np.ndarray, path: str | pathlib.Path):
|
|
bits = bits.astype(np.uint8)[: (len(bits) // 8) * 8] # trim to bytes
|
|
data = np.packbits(bits).tobytes()
|
|
pathlib.Path(path).write_bytes(data)
|
|
|
|
|
|
def txt_to_str(path: Union[str, pathlib.Path], encoding: str = "utf-8") -> str:
|
|
return pathlib.Path(path).read_text(encoding=encoding)
|