How to combine two 32-bit values into one 64-bit value in Python

1 Answer

0 votes
#!/usr/bin/env python3

"""
    Combine two 32-bit values into one 64-bit value.

    - The high 32 bits are shifted left by 32 positions.
    - The low 32 bits are OR'ed in.

    Python integers automatically expand to any size,
    so this behaves like uint64_t in C/C++.
"""

# ------------------------------------------------------------
# Function that combines two 32-bit integers into a 64-bit integer
# ------------------------------------------------------------
def combine_two32bit(high: int, low: int) -> int:
    # Shift the high part left by 32 bits and OR with the low part
    result = (high << 32) | low
    
    return result


# ------------------------------------------------------------
# Function that prints a 64-bit integer in hex with leading zeros
# ------------------------------------------------------------
def print_hex64(value: int) -> None:
    # Format as 16 hex digits (64 bits)
    print("0x" + format(value, "016X"))


# ------------------------------------------------------------
# Main program logic
# ------------------------------------------------------------
def main():
    high = 0x11223344   # Example high 32 bits
    low  = 0x55667788   # Example low 32 bits

    combined = combine_two32bit(high, low)

    print(f"High 32 bits: 0x{high:08X}")
    print(f"Low  32 bits: 0x{low:08X}")

    print("Combined 64-bit value:", end=" ")
    print_hex64(combined)


# Run the program
if __name__ == "__main__":
    main()


"""
run:

High 32 bits: 0x11223344
Low  32 bits: 0x55667788
Combined 64-bit value: 0x1122334455667788

"""

 



answered 12 hours ago by avibootz
edited 10 hours ago by avibootz

Related questions

...