David BS
David BS

Reputation: 53

Convert from ULong to Integer

I´m trying to convert a list of ULONG into an array of Integers.

The problem is related to HOW discard the MSB of ULONG! I had tried all kind of operations and all of them are raising an "Overflow Exception" error:

dim MyInteger as Integer = CInt(ULong_Number)     
dim MyInteger as Integer = Convert.ToInt32(ULong_Number)
dim MyInteger as Integer = Convert.ToUInt32(ULong_Number) 
dim MyInteger as Integer = ULong_Number xor &HFFFFFFFF00000000 xor &HFFFFFFFF00000000

I´m trying to avoid a convertion into a temporary byte array to, after, read each 4 bytes into the integer (the LIST if huge, almost 2 million numbers).

Does anyone have any idea to implicit convert this ULONG to INTEGER?

Thanks!

Upvotes: 0

Views: 741

Answers (1)

Blackwood
Blackwood

Reputation: 4534

If you are sure that the value of ULong_Number is not more than the maximum value of an integer (2^31 - 1, or &H7FFFFFFF), or you want to ignore any higher order bits (which would be an odd thing to do, but you are trying to fit an 8-byte number into 4 bytes), you could use this.

Dim MyInteger As Integer = CInt(ULong_Number And CULng(&H000000007FFFFFFF))

Upvotes: 1

Related Questions