r"""Encode a long to a two's complement little-endian binary string. Note that 0 is a special case, returning an empty string, to save a byte in the LONG1 pickling context. >>> encode_long(0) b'' >>> encode_long(255) b'\xff\x00' >>> encode_long(32767) b'\xff\x7f'
(x)
| 370 | f"Can't pickle {obj!r}: it's not the same object as {module_name}.{name}") |
| 371 | |
| 372 | def encode_long(x): |
| 373 | r"""Encode a long to a two's complement little-endian binary string. |
| 374 | Note that 0 is a special case, returning an empty string, to save a |
| 375 | byte in the LONG1 pickling context. |
| 376 | |
| 377 | >>> encode_long(0) |
| 378 | b'' |
| 379 | >>> encode_long(255) |
| 380 | b'\xff\x00' |
| 381 | >>> encode_long(32767) |
| 382 | b'\xff\x7f' |
| 383 | >>> encode_long(-256) |
| 384 | b'\x00\xff' |
| 385 | >>> encode_long(-32768) |
| 386 | b'\x00\x80' |
| 387 | >>> encode_long(-128) |
| 388 | b'\x80' |
| 389 | >>> encode_long(127) |
| 390 | b'\x7f' |
| 391 | >>> |
| 392 | """ |
| 393 | if x == 0: |
| 394 | return b'' |
| 395 | nbytes = (x.bit_length() >> 3) + 1 |
| 396 | result = x.to_bytes(nbytes, byteorder='little', signed=True) |
| 397 | if x < 0 and nbytes > 1: |
| 398 | if result[-1] == 0xff and (result[-2] & 0x80) != 0: |
| 399 | result = result[:-1] |
| 400 | return result |
| 401 | |
| 402 | def decode_long(data): |
| 403 | r"""Decode a long from a two's complement little-endian binary string. |
no test coverage detected
searching dependent graphs…