Commit
1 year ago
gh-37343: Add simple methods to convert to and from bytes for `ZZ` and finite fields I often have to work with the conversion of bytes / integers and currently do this by working with `int` types and then casting things to `ZZ` or elements of finite fields. This PR is a small addition to `Integer` and `FiniteField` types which allow this with simply functions which internally convert to / from `int` for the user so that things can be done naively from SageMath types. There's a TODO in the code which acknowledges that a faster method for `to_bytes` might be to work straight from the `gmp` object in cython for the integers, but it wasn't obvious to me how to do this. ### Examples ```py sage: ZZ.from_bytes(b'\x00\x10', byteorder='big') 16 sage: ZZ.from_bytes(b'\x00\x10', byteorder='little') 4096 sage: ZZ.from_bytes(b'\xfc\x00', byteorder='big', is_signed=True) -1024 sage: ZZ.from_bytes(b'\xfc\x00', byteorder='big', is_signed=False) 64512 sage: ZZ.from_bytes([255, 0, 0], byteorder='big') 16711680 sage: type(_) <class 'sage.rings.integer.Integer'> ``` ```py sage: (1024).to_bytes(2, byteorder='big') b'\x04\x00' sage: (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' sage: (-1024).to_bytes(10, byteorder='big', is_signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' sage: x = 1000 sage: x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' ``` ```py sage: F = GF(65537) sage: a = F.random_element() sage: a.to_bytes() b'\x00\n\x86' sage: F.from_bytes(_) 2694 sage: a 2694 ``` ```py sage: F = GF(3^10) sage: a = F.random_element(); a z10^8 + z10^7 + 2*z10^5 + 2*z10^4 + 2*z10^3 + z10^2 + z10 + 1 sage: a.to_bytes() b'$\xf7' sage: F.from_bytes(_) z10^8 + z10^7 + 2*z10^5 + 2*z10^4 + 2*z10^3 + z10^2 + z10 + 1 ``` ### :memo: Checklist - [x] The title is concise, informative, and self-explanatory. - [x] The description explains in detail what this PR is about. - [x] I have created tests covering the changes. - [x] I have updated the documentation accordingly. URL: https://github.com/sagemath/sage/pull/37343 Reported by: Giacomo Pope Reviewer(s): Giacomo Pope, grhkm21, Travis Scrimshaw
Author
Release Manager
Loading