Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UInt32 to Int32

If I have a VB.Net function that returns an Int32, but uses an unsigned int (UInt32) for calculations, etc. How can I convert a variable "MyUintVar32" with a value of say "3392918397 into a standard Int32 in VB.Net?

In c# if I just do a "return (int)(MyUintVar32);", I get -902048899, not an error.

I've tried several different methods. What is the difference in the way c# handles these conversions versus VB.Net?


1 Answers

I realize this is an old post, but the question has not been answered. Other people my want to know:

Dim myUInt32 As UInt32 = 3392918397  
Dim myInt32 As Int32 = Convert.ToInt32(myUInt32.ToString("X"), 16)  

the reverse operation:

myUInt32 = Convert.ToUInt32(myInt32.ToString("X"), 16)

Also, one can create a union structure to easily convert between Int32 and UInt32:

Imports System.Runtime.InteropServices

<StructLayout(LayoutKind.Explicit)> _    
  Public Structure UnionInt32  
  <FieldOffset(0)> _  
  Public IntValue As Int32  
  <FieldOffset(0)> _  
  Public UIntValue As UInt32  
End Structure  

Dim MyUnionInt32 as UnionInt32  
MyUnionInt32.UIntValue = 3392918397  
Dim IntVal as Int32 = MyUnionInt32.UIntValue  '= -902048899 

the reverse operation:

MyUnionInt32.IntValue = -902048000  
Dim UIntVal as UInt32 = MyUnionInt32.UIntValue  '= 3392919296  

Cheers, TENware

like image 76
user687979 Avatar answered Dec 31 '25 04:12

user687979



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!