C#中的字节到整数

jtb*_*jtb 13 .net c# sql-server

我正在从SQL Server表中读取一行.其中一列是tinyint类型.

我想将值转换为int或int32变量.

rdr.GetByte(j)
(byte) rdr.GetValue(j)
Run Code Online (Sandbox Code Playgroud)

......似乎是检索价值的唯一方法.但是如何将结果输入int变量?

Ste*_*ary 21

int value = rdr.GetByte(j);

不需要显式强制转换,因为byteto int是扩展转换(不存在数据丢失的可能性).

  • 我应该更具体一点.这就是我已经尝试过的.我得到一个"指定演员阵容无效".例外.我也尝试过:int value =(int)rdr.GetByte(j)和int value = Convert.ToInt(rdrGetByte(j)) (3认同)
  • 我同意@Jordao;听起来列“j”不是“字节”。尝试 `int value = Convert.ToInt(rdr.GetValue(j));` (2认同)

Dol*_*lph 12

请参阅BitConverter.ToInt32的文档(包含更多示例):

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
Run Code Online (Sandbox Code Playgroud)

  • 问题是询问如何将单个`byte`转换为`int`.`BitConverter`处理`byte`s的数组,而不是单个'byte`. (2认同)

Jor*_*dão 5

将 a 分配byteint作品:

int myInt = myByte;
Run Code Online (Sandbox Code Playgroud)

但也许您在内部 遇到异常IDataRecord.GetByte,在这种情况下,您应该检查用于访问数据记录的索引是否确实指向一tinyint列。您可以检查从 返回的类型GetValue。它应该是byte一个tinyint列。

Trace.Assert(rdr.GetValue(j).GetType() == typeof(byte));
Run Code Online (Sandbox Code Playgroud)

另一种选择是完全放弃脆弱的数字索引:

int myInt = rdr.GetByte(rdr.GetOrdinal(TheNameOfTheTinyintColumn))
Run Code Online (Sandbox Code Playgroud)