2015-09-06 80 views
0

如果我有一个字节数组表示从文件读取的数字,字节数组如何转换为Int16/short?C# - 将字节代表字符数转换为Int16

byte[] bytes = new byte[]{45,49,54,50 } //Byte array representing "-162" from text file 

short value = 0; //How to convert to -162 as a short here? 

尝试使用BitConverter.ToInt16(字节,0),但该值不正确。

编辑:寻找不使用字符串转换的解决方案。

+2

您需要将它们转换为字符串,然后解析字符串。 – willaien

+0

(短)BitConverter.ToInt32(字节) – adrianm

+0

实际上寻找一个解决方案,使用最少量的内存(试图避免字符串转换) – user2966445

回答

2

此功能进行一些验证,您可能能够排除。如果你知道你的输入数组总是包含至少一个元素并且该值将是一个有效的Int16,你可以简化它。

const byte Negative = (byte)'-'; 
    const byte Zero = (byte)'0'; 
    static Int16 BytesToInt16(byte[] bytes) 
    { 
     if (null == bytes || bytes.Length == 0) 
      return 0; 
     int result = 0; 
     bool isNegative = bytes[0] == Negative; 
     int index = isNegative ? 1 : 0; 
     for (; index < bytes.Length; index++) 
     { 
      result = 10 * result + (bytes[index] - Zero); 
     } 
     if (isNegative) 
      result *= -1; 
     if (result < Int16.MinValue) 
      return Int16.MinValue; 
     if (result > Int16.MaxValue) 
      return Int16.MaxValue; 
     return (Int16)result; 
    } 
0

像willaien说的,你想先把你的字节转换成一个字符串。

byte[] bytes = new byte[]{ 45,49,54,50 }; 
string numberString = Encoding.UTF8.GetString(bytes); 
short value = Int16.Parse(numberString); 

如果你不知道你的字符串可以解析,我建议使用Int16.TryParse

byte[] bytes = new byte[]{ 45,49,54,50 }; 
string numberString = Encoding.UTF8.GetString(bytes); 
short value; 

if (!Int16.TryParse(numberString, out value)) 
{ 
    // Parsing failed 
} 
else 
{ 
    // Parsing worked, `value` now contains your value. 
} 
+0

实际上寻找一个解决方案,使用LEAST量内存(试图避免字符串转换) – user2966445

+0

@ user2966445请参阅[Lorek's answer](http://stackoverflow.com/a/32425278/996081)。 – cubrr