public class Combine32bitTo64bit {
/**
int = 32-bit signed integer
long = 64-bit signed integer
We can treat them as unsigned using bit masking.
Combine two 32-bit values into one 64-bit value.
The usual pattern:
long result = ( (long)high << 32 ) | (low & 0xFFFFFFFFL);
Explanation:
- The 'high' 32-bit value is cast to long so it can be shifted safely.
- Shifting left by 32 moves it into the upper half of the 64‑bit integer.
- The 'low' 32-bit value is masked with 0xFFFFFFFFL to avoid sign extension.
- The two halves are OR'ed together.
*/
// Function that combines two 32-bit integers into a 64-bit integer
public static long combineTwo32bit(int high, int low) {
long high64 = ((long) high) << 32; // shift high part into upper 32 bits
long low64 = ((long) low) & 0xFFFFFFFFL; // mask to avoid sign extension
return high64 | low64;
}
// Function that prints a 64-bit value in hex with leading zeros
public static void printHex64(long value) {
System.out.printf("0x%016X%n", value);
}
public static void main(String[] args) {
int high = 0x11223344; // Example high 32 bits
int low = 0x55667788; // Example low 32 bits
long combined = combineTwo32bit(high, low);
System.out.printf("High 32 bits: 0x%08X%n", high);
System.out.printf("Low 32 bits: 0x%08X%n", low);
System.out.print("Combined 64-bit value: ");
printHex64(combined);
}
}
/*
run:
High 32 bits: 0x11223344
Low 32 bits: 0x55667788
Combined 64-bit value: 0x1122334455667788
*/