2015-09-06 75 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