これらの C# コードは CRC (CyclicRedundancyCheck) 用であり、正しく実行されます。
public static void ByteCRC(ref int CRC, char Ch)
{
int genPoly = 0x18005;
CRC ^= (Ch << 8);
for (int i = 0; i < 8; i++)
if ((CRC & 0x8000) != 0)
CRC = (CRC << 1) ^ genPoly;
else
CRC <<= 1;
CRC &= 0xffff;
}
public static int BlockCRC(String Block)
{
int BlockLen = Block.Length;
int CRC = 0;
for (int i = 0; i < BlockLen; i++)
ByteCRC(ref CRC, Block[i]);
return CRC;
}
//Invoking the function
String data="test"; //testing string
Console.WriteLine(BlockCRC(data).ToString("X4"));
それを Java コードに変換したいです。まず「ref」(C# で) の質問を解決するために、グローバル変数を使用し、その他の文法変更を行います。Java コードは次のとおりです。
public static int CRC;
public static void ByteCRC(int CRC, char Ch)
{
int genPoly = 0x18005;
CRC ^= (Ch << 8);
for (int i = 0; i < 8; i++)
if ((CRC & 0x8000) != 0)
CRC = (CRC << 1) ^ genPoly;
else
CRC <<= 1;
CRC &= 0xffff;
}
public static int BlockCRC(String Block)
{
int BlockLen = Block.length();
CRC = 0;
for (int i = 0; i < BlockLen; i++)
ByteCRC(CRC, Block.charAt(i));
return CRC;
}
//Invoking the function
String data="test"; //testing string
System.out.println(BlockCRC(data));
答えが 16 進数でないことはわかっていますが、正しい 10 進数ではなく、結果は 0 です。何が問題なのですか? 別の質問ですが、Java には C# の "ToString('X4')" と同じ機能がありますか?