我在讀一件設備生成的二進制日誌文件。我轉換爲短期有效的二進制數據?
我有一個字節[]的數據。
如果我需要閱讀兩個字節來創建一個短,我可以做這樣的事情:
short value = (short)(byte[1] << 8);
value += byte[2];
現在我知道的值是正確的有效數據。
我該如何知道文件是否搞砸了,可以說FF FF的值是在字節數組中的那兩個地方?
當我查看FF FF轉換爲短的結果值時,我得到-1。
這是FF FF的正常值嗎?還是計算機剛剛遇到了一些短的邊界並且無效的數據滾動?
對我而言,所有這些數字都是正面的。如果FF FF實際上是一個短-1,那麼我只需要驗證我的所有結果都是明示的。
謝謝
基思
順便說一句,我也讀其他數字數據類型。我會在這裏展示他們,只是因爲。 Read函數是讀取字節[]的基本部分。所有其他數據類型讀取都使用基本的Read()函數。
public byte Read()
{
//advance position and then return byte at position
byte returnValue;
if (_CurrentPosition < _count - 1)
{
returnValue= _array[_offset + ++_CurrentPosition];
return returnValue;
}
else
throw new System.IO.EndOfStreamException
("Cannot Read Array, at end of stream.");
}
public float ReadFloat()
{
byte[] floatTemp = new byte[4];
for (int i = 3; i >= 0; i--)
{
floatTemp[i] = Read();
}
float returnValue = System.BitConverter.ToSingle
(floatTemp, 0);
if (float.IsNaN(returnValue))
{
throw new Execption("Not a Number");
}
return returnValue;
}
public short ReadInt16()
{
short returnValue = (short)(Read() << 8);
returnValue += Read();
return returnValue;
}
public int ReadInt32()
{
int returnValue = Read() << 24;
returnValue += Read() << 16;
returnValue += Read() << 8;
returnValue += Read();
return returnValue;
}
乾淨的東西在二補的。 http://en.wikipedia.org/wiki/Twos_complement – 2008-11-06 16:16:18