Search code examples
javalong-integercpu-registersunsigned-long-long-int

Storing unsigned long value in two 16bit register


I want to store unsigned long value in two 16bit register.For example if I have long value (-2,147,483,648 to 2,147,483,647) then I'm using formula like:

v[0] = myValue % 65536
v[1] = myValue / 65536

To get value from register

outVal = reg0 + (reg1 * 65536)

But how to do for unsigned long which value range is from 0 to 4,294,967,295?


Solution

  • As commenter harold pointed out already, your formula doesn't even work correctly for negative numbers.

    You should do it bitwise instead of using math to avoid surprises (and speed things up in case the compiler didn't optimize it for you already).

    Splitting:

    v[0] = myValue & 0xFFFF
    v[1] = myValue >> 16    // this implicitly cuts off the lower 16 bits
                            // by shifting them away into the nirvana
    

    Joining:

    outVal = reg0 | (reg1 << 16)
    

    This now applies to both signed and unsigned (provided that all your variables have the same "sign type").


    Legend, in case your language (which you didn't specify) uses different operators:

    & is bitwise AND, | is bitwise OR, << and >> are bitwise shifting left/right (SHL/SHR), 0x marks a hexadecimal literal (you could use 65536 instead of 0xFFFF, but I think the hex literal makes it clearer where this magic number comes from).