BitConverter.ToInt16() produces unexpected result

时间:2015-11-12 11:43:39

标签: c# type-conversion

I have the following code about a checkers game function that handles moves:

public void convertMoveToIntValues(KeyValuePair<string, string> move, ref Int16 fromNumInt, ref Int16 toNumInt) {
    Byte[] fromNumTemp = { 0, 0 };
    Byte[] fromNum = {0,0,0,0};
    fromNumTemp = Encoding.ASCII.GetBytes(move.Key);
    fromNumTemp[0] -= 96;
    fromNumTemp[1] -= 48;
    fromNum[1] = fromNumTemp[0];
    fromNum[3] = fromNumTemp[1];
    fromNumInt = (Int16)(BitConverter.ToInt16(fromNum, 0) * 8 + BitConverter.ToInt16(fromNum, 2)); 
    Byte[] toNumTemp = {0,0};
    Byte[] toNum = { 0, 0, 0, 0 };
    toNumTemp = Encoding.ASCII.GetBytes(move.Value);
    toNumTemp[0] -= 96;
    toNumTemp[1] -= 48;
    toNum[1] = toNumTemp[0];
    toNum[3] = toNumTemp[1];
    toNumInt = (Int16)(BitConverter.ToInt16(toNum, 0) * 8 + BitConverter.ToInt16(toNum, 2));
}

public void Main() {
    Int16 a, b;
    convertMoveToInt(New KeyValuePair<string, string>("c3","b4"), a, b);

   Console.Writeline("The puppet moves from place no. " + a + " to place no. " + b);
}

I get the wrong solutions like: a=6912 and b=5120.

I use two kinds of Byte[], the first for an ASCII to Byte conversion, and then the other for the Byte to Int16 conversion. A good reference for the topic is: https://msdn.microsoft.com/en-us/library/system.bitconverter.toint16(v=vs.110).aspx

All things goes well until the last row, where it produces an incorrect result.

Could you help me getting the right answer?

2 个答案:

答案 0 :(得分:0)

我想你可能想要:

toNum[0] = toNumTemp[0];
toNum[2] = toNumTemp[1];

而不是:

toNum[1] = toNumTemp[0];
toNum[3] = toNumTemp[1];

(我还建议您编写一个接收string并返回Int16的方法,以避免两次编写相同的代码。

答案 1 :(得分:0)

现在我对此代码进行了一些更改,但实际上它并没有真正起作用。我有一个有8列8行的国际象棋桌。桌子的正式计数从a1开始 - 左下角到h8 - 右上角。在代码中,我将数据表示在一个数组中,该数组实际上从表的左上角开始,结尾是表的右下角。因此从给定的字母数字数据中获得解决该数组所需的数据是一种棘手的事情。 我请你查看以下将字母数字值转换为数组地址的方法,因为我会跳到一个不好的阶段(比如有时候4个单元格正好,而其他时候只有2个单元格正确)。

谢谢!

public void convertMoveToIntValues(KeyValuePair<string, string> move, ref Int16 fromNumInt, ref Int16 toNumInt)
{
    Int16 temp0, temp1;

    Byte[] fromNumTemp = { 0, 0 };
    Byte[] fromNum = {0,0,0,0};
    fromNumTemp = Encoding.ASCII.GetBytes(move.Key);
    fromNumTemp[0] -= 97;
    fromNumTemp[1] -= 49;
    fromNum[0] = fromNumTemp[0];
    fromNum[2] = fromNumTemp[1];
    temp0 = (Int16)(56 - (Int16)(BitConverter.ToInt16(fromNum, 2) * 8 + BitConverter.ToInt16(fromNum, 0)));
    fromNumInt = (temp0 > 0) ? temp0: (Int16)(-1 * temp0); 

    Byte[] toNumTemp = {0,0};
    Byte[] toNum = { 0, 0, 0, 0 };
    toNumTemp = Encoding.ASCII.GetBytes(move.Value);
    toNumTemp[0] -= 97;
    toNumTemp[1] -= 49;
    toNum[0] = toNumTemp[0];
    toNum[2] = toNumTemp[1];
    temp1 = (Int16)(56 - (Int16)(BitConverter.ToInt16(toNum, 2) * 8 + BitConverter.ToInt16(toNum, 0)));
    toNumInt = (temp1 > 0) ? temp1: (Int16)(-1 * temp1);
}