Skip to content

Instantly share code, notes, and snippets.

@ascopes
Created June 1, 2025 11:10
Show Gist options
  • Select an option

  • Save ascopes/bf457458d865bb91098ea9a53f45f004 to your computer and use it in GitHub Desktop.

Select an option

Save ascopes/bf457458d865bb91098ea9a53f45f004 to your computer and use it in GitHub Desktop.
Python encoding of "octal numbers" in tar files
import typing as t
@t.final
class TarOctalAsciiNumber(int):
__slots__: t.Sequence[str] = ()
def __new__(cls, value: int) -> t.Self:
return super().__new__(cls, value)
def to_octal_ascii(self, size: int) -> bytes:
data = oct(self)[2:].encode("ascii") + b"\0"
if len(data) > size:
raise ValueError(f"Cannot fit {data} into {size} bytes")
lpad = b"\0" * (len(data) - size)
return lpad + data
@classmethod
def from_octal_ascii(cls, data: bytes) -> t.Self:
string = data.strip(b" \0").decode("ascii")
value = int(string, 8)
return cls(value)
def __repr__(self) -> str:
return f"{type(self).__name__}(value={super()!r}}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment