C# .NET BitConverter doesn't work for SQL Server stored VarBinary read -


we're storing integer in our sql server 2008 database varbinary. using entity framework, when reading varbinary value, returns, c# code, byte array.

yes. know doesn't make sense store integer varbinary in database right off. there reason storage method.

hence, integer value of 10762007 0xa43717 if examined table select statement. actual value in our code after reading byte array is:

byte[] b = new byte[]{0, 164, 55, 23}; 

now, uninitiated might think simple conversion integer be:

int myint = bitconverter.toint32(b); 

...which not produce desired results.

i figured problem out doing following:

string bitstring = string.empty; string[] bitarray = new string[4];  ( int = 0; < 4; i++) {    bitarray[i] = convert.tostring((int)b[i],2).padleft(8,"0");    bitstring += bitarray[i]; }  int therealint = convert.toint32(bitstring,2); 

which taking integer representation of hex values, converting them bit string, appending them appropriately, , converting big, giant bit string integer.

this works seems i'm doing more work need to. there easier way perform action? basically, we're storing integer varbinary in database, , wanting convert same integer in c# code.

just try

var myint = bitconverter.toint32(b.reverse().toarray(),0); 

or

var myint = ipaddress.networktohostorder(bitconverter.toint32(b,0)); 

it endianness


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -