Combining Integers to Make a Long

  • Thread starter Thread starter TC
  • Start date Start date
T

TC

Here is a puzzle. I need a function Z = F(X,Y) where X and Y are
signed 32-bit integers and Z is a 64-bit integer (either signed or
unsigned -- I don't care). The function has to meet only one
requirement: Z must be unique for each unique combination of X and Y.

I thought this would be easy, but it is harder than I expected. So
far, the best I can do is this:

Z = 2147483648 + 4294967296 * X + Y

However, that seems inelegant. I think there may be a better solution
which uses bitwise operators, but I can't find it. Any suggestions?


-TC
 
(CLng(x) << 32) Or y

Thanks for the suggestion, but that technique has trouble with
negative numbers. Note that when y=-1, it always evaluates to -1,
regardless of x.

-TC
 
TC said:
Here is a puzzle. I need a function Z = F(X,Y) where X and Y are
signed 32-bit integers and Z is a 64-bit integer (either signed or
unsigned -- I don't care). The function has to meet only one
requirement: Z must be unique for each unique combination of X and
Y.

I thought this would be easy, but it is harder than I expected. So
far, the best I can do is this:

Z = 2147483648 + 4294967296 * X + Y

However, that seems inelegant. I think there may be a better
solution which uses bitwise operators, but I can't find it. Any
suggestions?

Imports System.Runtime.InteropServices

<StructLayout(LayoutKind.Explicit)> _
Structure t
<FieldOffset(0)> Public i1 As Int32
<FieldOffset(4)> Public i2 As Int32
<FieldOffset(0)> Public l As Int64


Sub New(ByVal i1 As Integer, ByVal i2 As Integer)
Me.i1 = i1
Me.i2 = i2
End Sub
Shared Function MakeLong( _
ByVal i1 As Integer, ByVal i2 As Integer) As Long

Return (New t(i1, i2)).l
End Function
End Structure


MsgBox(t.MakeLong(5, 10))


Armin
 
Will this do?

Dim a As Integer = -1
Dim b As Integer = 345345
Dim z(0 To 7) As Byte
Array.Copy(BitConverter.GetBytes(a), 0, z, 0, 4)
Array.Copy(BitConverter.GetBytes(b), 0, z, 4, 4)
Dim result As Long = BitConverter.ToInt64(z, 0)
MsgBox(result)

-Blake
 
you are right, my mistake due to sloppy testing.

z = (CLng(x) << 32) Or (CLng(y) And &HFFFFFFFFL)

The above prevents all high order 1-bits in z when y is negative.
 
You guys rock. All three techniques seem to work, and they are all
better than my original function. Thanks.

-TC
 
Back
Top