Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

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

1 Answer

0 votes
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

*/

 



answered Jun 22 by avibootz
edited Jun 23 by avibootz

Related questions

...