ネコと和解せよ

pythonの符号なしintとバイナリをいい感じに相互変換する

pythonでint128やらint256を扱ったときに、JsonやDBへそのまま書き出せない。
blobに変換して書きだすとよろしいようなので、関数を作った。

import math

def toBlobUint(n):
    """uintをバイナリに変換
    """
    if n==0:
        return int.to_bytes(n,1,byteorder="big",signed=False)
    else:
        return int.to_bytes(n,int(1+math.log2(n)//8),byteorder="big",signed=False)

def fromBlobUint(n):
    """バイナリ文字列をuintへ変換
    """
    return int.from_bytes(n,byteorder="big",signed=False)

実行する。

print(toBlobUint(9999),fromBlobUint(b'aaaaa'),fromBlobUint(toBlobUint(8888)))

b"'\x0f" 418245599585

バイナリの長さを調節してくれるところがチャームポイント。

追記2020/12/19

0を変換できないので直しました。