Measurement Studio for .NET Languages

cancel
Showing results for 
Search instead for 
Did you mean: 

VB.NET Hex to Int Conversion

I am having problem with CINT function. I am trying to convert a Hex Number to integer. For positive numbers it is behaving correctly. For Negative numbers instead of returning negative numbers, its returning a positive number. Let me tell you how I am using it in my code.

Dim intResult As Integer
intResult = CInt("&H" + "FF00")

Output: 65280
the output should be -256

I found a work around for this problem but i need to hardcore hex value in the code. i.e
Dim test As Object
Dim intResult As Integer

test = &HFF00S
intresult = CInt(test)
Output: -256

I need to append "&H" to the hex number in my code because the hex number keeps on changing. Can anyone tell me how to deal Hex values that gives negative integer values?

Thanks for you time.
0 Kudos
Message 1 of 5
(41,935 Views)
Integers are 32 bits, and four hex digits only describe the least 16 bits. The actual hex representation of -256 over 32 bits would be FFFFFF00. If you try the expression CInt("&HFFFFFF00") you should get the expected result. The difference between the case you build the string representation yourself and when you hardcode the hex value is the "S". In the case you hardcoded the value, you expressly identified the constant as a short integer. When you convert from a short int to an int, the most significant bit is left extended to preserve the sign of the number. So CInt(&HFF00S) gives -256, CInt(&HFFFFFF00) should give 65280.
0 Kudos
Message 2 of 5
(41,917 Views)
Thanks for the response. I am still not very clear. I am getting four hex digits as string. I have to work with both positive and negative numbers. what variable(Short or Integer) do i need to take to hold the number.

In VB: Dim intValue as integer
intValue = CInt("&H" + "FF00")
Output : -256

How to Implement the same functionality in VB.NET.

Thanks for your time. I appreciate your help.
0 Kudos
Message 3 of 5
(41,907 Views)
The VB Val function may do what you're looking for. For example, in VB.NET:

Dim input As String = "&HFF00"
Dim value As Integer = Val(input)
Console.WriteLine(value)

Output: -256

- Elton
0 Kudos
Message 4 of 5
(41,899 Views)
You can use the old IIF instruction and to joggle with characters

Dim a As String = "&HFF00"
Dim b As Integer
b = CInt(IIf(CInt("&H" & a.Substring(2, 1)) > 7 And a.Length = 6, "&HFFFFFFFFFFFF" & a.Substring(2), a))

you can check it with also
Dim a As String = "&HF00"
Dim a As String = "&H8F00" ' it is a neg number
Dim a As String = "&H7F00" ' is is a pos number
0 Kudos
Message 5 of 5
(41,555 Views)