Reputation: 2047
We're storing an integer in our SQL Server 2008 database as a VARBINARY
. Using Entity Framework, when reading this VARBINARY
value, it returns, to the C# code, a byte array.
Yes. I know it doesn't necessarily make sense to store the integer as a VARBINARY
in the database right off. There is a good reason for this storage method.
Hence, the integer value of 10762007 would actually be 0xA43717 if you examined the table with a SELECT
statement. The actual value we get in our code after reading it into a byte array is:
byte[] b = new byte[]{0, 164, 55, 23};
Now, the uninitiated might think that a simple conversion back to an integer would be:
int myInt = BitConverter.ToInt32(b);
...which does not produce the desired results.
I figured this problem out by doing the following:
string bitString = string.Empty;
string[] bitArray = new string[4];
for ( int i = 0; i < 4; i++)
{
bitArray[i] = Convert.ToString((int)b[i],2).PadLeft(8,"0");
bitString += bitArray[i];
}
int theRealInt = Convert.ToInt32(bitString,2);
Which is essentially taking my integer representation of the hex values, converting them to a bit string, appending them appropriately, and then converting the big, giant bit string back to an integer.
This works but it seems like I'm doing more work than I need to. Is there some easier way to perform this action? Basically, we're storing an integer as a VARBINARY
in the database, and then wanting to convert this back to the same integer in C# code.
Upvotes: 0
Views: 1053
Reputation: 120508
Jon Skeet has a drop-in replacement for BitConverter (MiscUtil.Conversion.EndianBitConverter
) that deals with endian issues, and it can be found in the Miscellaneous Utility Library
Upvotes: 0
Reputation: 35363
Just try
var myInt = BitConverter.ToInt32(b.Reverse().ToArray(),0);
or
var myInt = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(b,0));
It is about Endianness
Upvotes: 2