Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte to integer in C#

I am reading a row from a SQL Server table. One of the columns is of type tinyint.

I want to get the value into an int or int32 variable.

rdr.GetByte(j)
(byte) rdr.GetValue(j)

...seems to be the only way to retrieve the value. But how do I get the result into an int variable?

like image 867
jtb Avatar asked Jun 15 '10 15:06

jtb


5 Answers

int value = rdr.GetByte(j);

An explicit cast is not required, because a byte to int is a widening conversion (no possibility of data loss).

like image 133
Stephen Cleary Avatar answered Oct 05 '22 04:10

Stephen Cleary


See the documentation for BitConverter.ToInt32 (contains more examples):

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
// Output: int: 25
like image 27
Dolph Avatar answered Oct 05 '22 04:10

Dolph


Assigning a byte to an int works:

int myInt = myByte;

But maybe you're getting an exception inside IDataRecord.GetByte, in which case you should check that the index you're using to access the data record really points to a tinyint column. You can check the type returned from GetValue. It should be a byte for a tinyint column.

Trace.Assert(rdr.GetValue(j).GetType() == typeof(byte));

Another option is to forego the fragile numeric index altogether:

int myInt = rdr.GetByte(rdr.GetOrdinal(TheNameOfTheTinyintColumn))
like image 22
Jordão Avatar answered Oct 05 '22 05:10

Jordão


(int)rdr.GetByte(j)
like image 40
abatishchev Avatar answered Oct 05 '22 04:10

abatishchev


Casting the byte to int should work just fine:

int myInt = (int) rdr.GetByte(j);

Since C# supports implicit conversions from byte to int, you can alternatively just do this:

int myInt = rdr.GetByte(j);

Which one you choose is a matter of preference (whether you want to document the fact that a cast is taking place or not). Note that you will need the explicit cast if you want to use type inference, or otherwise myInt will have the wrong type:

var myInt = (int) rdr.GetByte(j);
like image 33
Heinzi Avatar answered Oct 05 '22 06:10

Heinzi