Commit 9991759
Release Manager
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
```
### 📝 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: #37343
Reported by: Giacomo Pope
Reviewer(s): Giacomo Pope, grhkm21, Travis Scrimshaw
File tree
3 files changed
+3
-3
lines changed- src/sage/rings
- finite_rings
3 files changed
+3
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
143 | 143 | | |
144 | 144 | | |
145 | 145 | | |
146 | | - | |
| 146 | + | |
147 | 147 | | |
148 | 148 | | |
149 | 149 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2118 | 2118 | | |
2119 | 2119 | | |
2120 | 2120 | | |
2121 | | - | |
| 2121 | + | |
2122 | 2122 | | |
2123 | 2123 | | |
2124 | 2124 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1575 | 1575 | | |
1576 | 1576 | | |
1577 | 1577 | | |
1578 | | - | |
| 1578 | + | |
1579 | 1579 | | |
1580 | 1580 | | |
1581 | 1581 | | |
| |||
0 commit comments