Skip to main content

Wrapper de int para numeros naturales grandes con slicing por bits

Project description

HugeNat

HugeNat es un wrapper ligero sobre int que mantiene la semántica de los enteros de Python para números naturales (ℕ₀) y añade indexado/slicing por bits, vistas NumPy y un núcleo listo para Numba.

Instalación

pip install HugeNats

Creación rápida

import numpy as np
from hugenat import HugeNat

# Desde un entero no negativo
x = HugeNat(123456789)

# Desde limbs (uint64, little-endian: limb 0 es LSB)
limbs = np.array([0xFFFFFFFFFFFFFFFF, 0x1], dtype=np.uint64)
y = HugeNat(limbs)

# Desde una lista/tupla de enteros (se convierten a uint64 y se recortan ceros finales)
z = HugeNat([1, 2, 3])

API tipo int

  • int(x), bool(x), hash(x), str(x) reflejan al entero interno.
  • Métodos compatibles: bit_length(), bit_count(), to_bytes(), from_bytes().
  • Aritmética y bitwise devuelven siempre HugeNat y rechazan resultados negativos en restas.
a = HugeNat(10)
b = HugeNat(7)

int(a + b)        # 17
int(a * b)        # 70
int(a // b)       # 1
int(a % b)        # 3
int(a << 3)       # 80
int(a | b), int(a & b), int(a ^ b)

Indexado de bits

  • Convención: LSB = índice 0. Índices negativos son relativos a bit_length().
  • Fuera de rango devuelve 0.
  • ~x no está definido y lanza ValueError.
x = HugeNat(0b1101101)  # 109

x[0]    # 1 (LSB)
x[-1]   # 1 (MSB)
x[100]  # 0

Slicing de bits

  • step en {None, 1} usa ruta rápida: normaliza como Python, recorta a [0, nbits] y recompacta para que el bit start pase a ser el bit 0.
  • Cualquier otro step (salvo 0) usa ruta general con semántica completa de slicing de listas y reempaquetado LSB-first.
  • step == 0 -> ValueError.
x = HugeNat(0b1101101)

x[0:3]        # bits 0..2 -> 0b101 (5)
x[2:5]        # 0b110 (6)
x[0:7:2]      # toma cada 2 bits -> 0b10011 (19)
x[5:0:-2]    # slicing con paso negativo

Vista de bits como array

bits(order="msb->lsb" | "lsb->msb", length=None) devuelve np.ndarray de uint8.

x = HugeNat(0b1011)

np.asarray(x.bits())                  # array([1, 0, 1, 1], dtype=uint8)
np.asarray(x.bits(order="lsb->msb")) # array([1, 1, 0, 1], dtype=uint8)
np.asarray(x.bits(length=8))          # padding a la izquierda: 00001011

Cadena de bits agrupados

bits_str(order="msb->lsb" | "lsb->msb", group=64, sep=" ") para depurar o mostrar.

x = HugeNat(0x0123456789ABCDEFFEDCBA9876543210)

x.bits_str(group=4)          # grupos de 4 bits
x.bits_str(group=8)          # grupos de 1 byte
x.bits_str(order="lsb->msb", group=8)

Bytes ida y vuelta

x = HugeNat(2**20 + 123)
length = (x.bit_length() + 7) // 8

b = x.to_bytes(length=length, byteorder="big", signed=False)
y = HugeNat.from_bytes(b, byteorder="big", signed=False)

assert int(y) == int(x)

Rotaciones de bits

Las rotaciones usan el ancho natural (bit_length()):

x = HugeNat(0b100101)

int(x.rotl(2))  # 0b010110
int(x.rotr(2))  # 0b011001

HugeNat(0).rotl(5)  # -> HugeNat(0)

Núcleo Numba-friendly

to_core() expone (limbs, nbits) contiguos en little-endian por palabra de 64 bits; from_core() reconstruye el mismo valor. Útil para kernels njit sin dependencias externas.

from numba import njit

x = HugeNat(2**130 + 5)
limbs, nbits = x.to_core()

@njit
def popcount_core(limbs, nbits):
    total = 0
    for i in range(limbs.size):
        total += int(limbs[i]).bit_count()
    return total

popcount_core(limbs, nbits)
y = HugeNat.from_core(limbs, nbits)
assert int(y) == int(x)

Contrato de dominio

  • Solo enteros >= 0 o arrays 1D de limbs uint64 (little-endian). Valores negativos o dimensiones distintas lanzan ValueError.
  • Los ceros de mayor peso se recortan automáticamente.
  • Las restas que producirían negativos lanzan ValueError.

Desarrollo

  • Dependencias de desarrollo: pytest, numpy.
  • Ejecuta la batería completa: pytest -q.

Las demostraciones completas viven en HugeNat_demo.ipynb y cubren todos los ejemplos anteriores.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

hugenats-0.1.2.tar.gz (12.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

hugenats-0.1.2-py3-none-any.whl (7.9 kB view details)

Uploaded Python 3

File details

Details for the file hugenats-0.1.2.tar.gz.

File metadata

  • Download URL: hugenats-0.1.2.tar.gz
  • Upload date:
  • Size: 12.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for hugenats-0.1.2.tar.gz
Algorithm Hash digest
SHA256 7752909d7d9a7c3233b2607e163f22fd0301c8fd66d88455eb60e68d7820a7fe
MD5 c0f98d56c04fc1bc666e65ccd1aa23e1
BLAKE2b-256 d448cee4f97bcabfcfa6209752bb3fd37a7aa666a1d255d6f72df5d3640bfeb6

See more details on using hashes here.

File details

Details for the file hugenats-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: hugenats-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 7.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for hugenats-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 8a8e4a9c09726c810183236738d43e7f5c3b12c4e1e5fd99afb3d482063ad54c
MD5 706f445c821bd2cec6c728b9cd66942f
BLAKE2b-256 d3b044ddd373d5b7f04e74e205c886b4f67a79ea01b9751a49e6624f1becb06e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page