问题
I have the need to convert a hex string into an integer using C#. I've tried all of the suggestions on SO including this one and many others. All of them throw the same or roughly the same... error. Value was either too large or too small for an Int32
(same for Int64
).
I can get the desired result in SQL Server 2008 with the following code:
select convert(int, 0x1B1D3E1B22176145272C1631282D221D30)
However THIS C# code
Int64.Parse("1B1D3E1B22176145272C1631282D221D30", NumberStyles.HexNumber)
Int32.Parse("1B1D3E1B22176145272C1631282D221D30", NumberStyles.HexNumber)
...yields the errors described above. Thoughts?? Solutions?
UPDATE: The SQL Code above yields the following integer.. 555949360. With every record I can find, the sql conversion yields a unique Integer. So the new question (I guess) is.. how to replicate the results of the SQL Convert function on this hex data?
回答1:
While SQL Server does not error, its not giving you the correct answer. Its truncating the hex string to just the lower 32bits
select convert(int, 0x2D221D30) = 757210416
select convert(int, 0x1B1D3E1B22176145272C1631282D221D30) = 757210416
If you change this to bigint you get different results:
select convert(bigint, 0x2D221D30) = 757210416
select convert(bigint, 0x1B1D3E1B22176145272C1631282D221D30) = 3176780635782126896
回答2:
Your number is too big. It's about 9.2264939914744E+39 when Int64.MaxValue
is 9,223,372,036,854,775,807.
Try to use BigInteger.Parse method.
回答3:
I tried it on wolfram that is a 133bit number. You can try using a BigInteger(Byte[]) in c#
This is the binary number in case you wanted to see it: 1101100011101001111100001101100100010000101110110000101000101001001110010110000010110001100010010100000101101001000100001110100110000
回答4:
You (nor SQL Server) can decode 34 bytes into a 4 byte integer. Hexedecimal strings represent each byte of data as two characters, one for the high nibble (4 bits), one for the low nibble.
You can use a HexEncoding class I wrote to decode this into bytes or write your own.
see also http://en.wikipedia.org/wiki/Hexidecimal
来源:https://stackoverflow.com/questions/8493890/conversion-of-long-hex-string-to-integer-not-working-as-expected-works-in-sql