Integer.Parse

L

lgbjr

hi All,

I have a question regarding Integer.Parse. I'm doing the following:

Dim H_cid1, H_cid2 as String
Dim I_cid1, I_cid2 as Integer

H_cid1 = "BFEBFBFF"
H_cid2 = "00000F29"

I_cid1 = Integer.Parse(H_cid1, Globalization.NumberStyles.HexNumber)
I_cid2 = Integer.Parse(H_cid2, Globalization.NumberStyles.HexNumber)

I_cid1 should be 3219913727. However, what I'm getting is -1075053569 (which
is FFFFFFFFBFEBFBFF in Hex).

I_cid2 should be 3881 and I_cid2 does equal 3881.

Anyone know why I_cid1 is not being converted correctly (or if it's being
converted correctly, why I'm not getting the value I expect!)

TIA,
Lee
 
A

Andrew Morton

Anyone know why I_cid1 is not being converted correctly (or if it's being
converted correctly, why I'm not getting the value I expect!)

A variable of integer type holds values from -2^31 to 2^31-1. A decimal
variable would be large enough - see the help for its range.

Andrew
 
S

Shane

Your answer comes down to 2's compliment arithematic. Yes, I'm old
enough that they still taught us about that in college.

Any value greater than 7FFFFFFF is treated as a negative number with
signed integers. The leftmost bit is the sign.

The value is calculated by subtracting your hex string from FFFFFFFF
and adding 1 for the negative value

FFFFFFFF
-FFFFFFFF
---------
00000000 + 1 = -1

FFFFFFFF
-BFEBFBFF
--------
40140400 + 1 = -1075053569

The decimal call by Andrew is one correct answer, because the decimal
uses 16 bytes instead of only four bytes, so the negative bit is not an
issue. A long may work as well; I believe that a long is 8 bytes. An
unsigned integer may still work for your needs, but I don't remember if
the CLR supports it.

Shane
 
L

lgbjr

Thanks guys!

I thought I had verified I was within the integer range, but apparently not.
I switched to long and all is well. Shane, thanks for the 2's compliment
math lesson! Though switching to long fixed the problem, it's nice to know
where the negative number was coming from!

Thanks Again!
Lee
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top