UInt32 to Int32

情到浓时终转凉″ 提交于 2021-01-27 18:46:15

问题


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:


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




回答2:


3392918397 is too big to fit into a signed 32-bit integer, that's why it is coming out negative, because the most significant bit of 3392918397 is set.

1100 1010 0011 1011 1101 0011 0111 1101

If you want to maintain integers of this proportion inside a signed integer type, you'll need to use the next size up, a 64-bit signed integer.




回答3:


It's not an optimal solution, but you can use BitConverter to get a byte array from the uint and convert the byte array to int.

Dim myUInt32 As UInt32 = 3392918397
Dim myInt32 As Int32 = BitConverter.ToInt32(BitConverter.GetBytes(myUInt32), 0)



回答4:


You can't convert 3392918397 into an Int32 since that number is too large to fit in 31 bits. Why not just change the function to return a UInt32?




回答5:


Or after doing the Uint32 work check it against MAXINT and 0.

If > MAXINT and < 0 then you're ok. If not you "overflowed" and should throw an exception.

I don't remember if MAXINT is defined. You can use: 2^31 - 1 instead.



来源:https://stackoverflow.com/questions/210383/uint32-to-int32

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!