杰瑞科技汇

Python中如何表示64位整数?

Of course! In Python, the concept of a "64-bit integer" is handled very differently than in languages like C++ or Java. Here's a complete guide.

The Short Answer: Python Integers are Arbitrary-Precision

In Python, the standard int type is not a fixed 64-bit integer. It is an arbitrary-precision integer.

This means:

  • No Fixed Size: A Python int can grow to be as large as your computer's memory allows. It won't "wrap around" or overflow after 2^64.
  • No Performance Penalty for Small Numbers: For small numbers (those that fit in 64 bits), Python's int is just as fast and efficient as a 64-bit integer in other languages.

This is one of Python's greatest strengths for scientific computing, data science, and cryptography.


How to Create a 64-bit Integer (The Explicit Way)

Even though Python's int is arbitrary-precision, you might need to interact with systems that require a 64-bit integer (e.g., reading from a binary file, using a C library, or network protocols).

In these cases, you use the int constructor and specify the base as 0 to allow for prefix notation (like 0x for hex) and then use a literal that fits within 64 bits.

A 64-bit signed integer can hold values from -2⁶³ to 2⁶³ - 1.

  • Minimum value: -9,223,372,036,854,775,808
  • Maximum value: 9,223,372,036,854,775,807

Here are examples of creating integers within this range:

# Decimal
large_int = 9223372036854775807
small_int = -9223372036854775808
# Hexadecimal (0x prefix)
hex_int = 0x7FFFFFFFFFFFFFFF # This is the max positive 64-bit signed int
# Octal (0o prefix)
oct_int = 0o777777777777777777 # Also the max positive 64-bit signed int
# Binary (0b prefix)
bin_int = 0b111111111111111111111111111111111111111111111111111111111111111 # Also the max
print(f"Decimal: {large_int}")
print(f"Hex:     {hex_int}")
print(f"Octal:   {oct_int}")
print(f"Binary:  {bin_int}")
# They are all the same type and value
print(type(large_int))
print(large_int == hex_int) # True

What happens if you go outside the 64-bit range? Nothing special! The integer just gets bigger. It remains a standard Python int.

# This is perfectly valid in Python
too_large = 9223372036854775808 # One more than the max 64-bit signed int
print(f"This number is: {too_large}")
print(f"It is still a type: {type(too_large)}")

The struct Module for True 64-bit Packing/Unpacking

When you need to serialize a Python integer into a fixed-size 64-bit binary format (e.g., for a file or network), you use the struct module. This module handles the conversion between Python values and C-style data types.

  • struct.pack(): Converts a Python value into a bytes object.
  • struct.unpack(): Converts a bytes object back into a Python value.

The format character for a 64-bit signed integer is q.

import struct
# The number we want to convert
my_number = 123456789
# Pack the integer into 8 bytes (64 bits)
# 'q' means a signed long long (64-bit)
# The '<' means little-endian byte order
packed_data = struct.pack('<q', my_number)
print(f"Original integer: {my_number}")
print(f"Packed bytes:    {packed_data}")
print(f"Length of packed data: {len(packed_data)} bytes") # 8 bytes
# Unpack the bytes back into an integer
unpacked_number = struct.unpack('<q', packed_data)[0]
print(f"Unpacked integer: {unpacked_number}")
print(f"Are they equal? {my_number == unpacked_number}")

Handling Overflow with struct If you try to pack a number that is too large for a 64-bit signed integer, Python will raise an struct.error.

import struct
try:
    # This number is too big for a signed 64-bit int
    too_big = 9223372036854775808
    struct.pack('<q', too_big)
except struct.error as e:
    print(f"Error: {e}")

NumPy: Fixed-Size Integers for Performance

For numerical computing and data analysis, the NumPy library provides fixed-size integer types that map directly to C types. This is useful for creating arrays of a specific memory size and for performance-critical operations.

The NumPy type for a 64-bit signed integer is np.int64.

import numpy as np
# Create a NumPy int64
np_int = np.int64(123456789)
print(f"NumPy int64 value: {np_int}")
print(f"NumPy int64 type:  {type(np_int)}")
# You can check the size in bits
print(f"Size in bits:      {np_int.nbytes * 8}") # nbytes gives bytes, so *8 for bits
# NumPy arrays enforce the type
arr = np.array([1, 2, 3, 4], dtype=np.int64)
print(f"NumPy array: {arr}")
print(f"Array dtype: {arr.dtype}")
# Trying to put a too-large number in a np.int64 array will cause overflow or truncation
# It will wrap around, which is different from Python's int behavior
arr[0] = 9223372036854775808 # One more than max
print(f"Array after overflow: {arr}") # This will likely show a negative number

Summary Table

Concept How to Use Key Characteristics Best For
Python int my_var = 123 Arbitrary-precision. No fixed size. Handles huge numbers. No overflow. General purpose programming, math, cryptography, when numbers can be very large.
struct Module struct.pack('<q', my_int) Serializes a number to a fixed-size binary block (8 bytes). Raises an error on overflow. File I/O, network protocols, interfacing with low-level C libraries.
NumPy np.int64 np.int64(123) or dtype=np.int64 Fixed-size 64-bit integer. Part of NumPy arrays. Can wrap around on overflow. Numerical computing, data analysis, performance-critical array operations.

Final Takeaway

For most Python programming, you don't need to worry about 64-bit integers. Just use the standard int. You only need to reach for struct or NumPy when you have specific requirements for binary data representation or high-performance numerical arrays.

分享:
扫描分享到社交APP
上一篇
下一篇