将c#转换为java时的签名/未签名情况

时间:2012-03-26 15:34:27

标签: c# java

我目前正在将以下代码转换为c#:

中的java
    public static byte MakeCS(byte[] arr)
    {
        byte cs = 0;
        for (int i = 0; i < arr.Length; i++)
        {
            cs += arr[i];
        }
        return cs;
    }

我天真的谈话只是将arr.Length改为arr.length;)

然而,这给了我不正确的校验和,因为java有签名字节而c#有无符号的(我尝试将c#代码更改为sbyte并且工作正常)。

处理这种情况的正确方法是什么?我知道我可以&#34;转换&#34;一个java字节,由bit进行无符号和0xFF,但我不知道该怎么做!

谢谢!

3 个答案:

答案 0 :(得分:2)

您只需要更改返回值并返回返回类型int

return cs & 0xFF;

您无需更改cs的类型,因为在使用0xFF后,无论是intshort还是long,都会产生相同的结果。您也不需要屏蔽每个值。

public static void main(String... args) {
    byte[] bytes = { 1, -128, -1 }; // check sum is -128 or 0x80 or 128 (unsigned)
    System.out.println("makeCS "+ makeCS(bytes));
    System.out.println("makeCS2 "+ makeCS2(bytes));
    System.out.println("makeCS3 "+ makeCS3(bytes));
}

public static int makeCS(byte... arr) {
    byte cs = 0;
    for (byte b : arr)
        cs += b;
    return cs & 0xFF;
}

public static int makeCS2(byte[] arr)
{
    int cs = 0;
    for (int i = 0; i < arr.length; i++)
    {
        int add = arr[i];
        cs += (0xFF & add);
        cs &= 0xFF;
    }
    return cs;
}

public static short makeCS3(byte[] arr)
{
    short cs = 0;
    for (int i = 0; i < arr.length; i++)
    {
        cs += arr[i];
    }
    return cs;
}

打印

makeCS 128
makeCS2 128
makeCS3 -128

答案 1 :(得分:1)

试试这个:

public static byte MakeCS(byte[] arr)
{
    int cs = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        int add = arr[i];
        cs += (0xFF & add);
        cs &= 0xFF;
    }
    return cs;
}

这会在将int添加到CS之前截断它的符号部分,并且再次截断8位后的所有内容以模拟无符号加法。

答案 2 :(得分:0)

听起来你期望使用c#byte的全部8位来完成总和。为了正确移植到Java,您需要选择一个至少具有相同精度的类型。 Java中最接近的类型是short

public static short MakeCS(byte[] arr)
{
    short cs = 0;
    for (int i = 0; i < arr.length; i++)
    {
        cs += arr[i];
    }
    return cs;
}

注意:虽然这不是一个完美的端口。它打开了在C#中溢出的代码不会在Java版本中溢出的可能性,因为Java short具有更高的C#byte精度。