4

私はDelphiの知識がまったくないということから始めましょう...

delphiで記述された古いアプリをJavaに移植しようとしていますが、機能していません...

私は2バイトにいくつかの二項演算を行うこの関数を持っています。Delphiのコードは次のとおりです。

function  TMainForm.mixthingsup(x, y: byte): word;
var
counter: byte;
answer1, answer2: byte;

begin
answer1             := $9D xor x;

for counter := 1 to 8 do
begin
    if (answer1 and $80) = $80 then
        answer1 := (answer1 shl 1) xor $26
    else
        answer1 := (answer1 shl 1);
end;

answer2             := answer1 xor y;

for counter := 1 to 8 do
begin
    if ((answer2 and $80) = $80) then
        answer2 := ((answer2 shl 1) xor $72)
    else
        answer2 := (answer2 shl 1);
end;

Result := (answer1 shl 8) or answer2;
end;

そして、これが私のJavaコードです。

public static String mixthingsup(String data)
{
 byte[] conv=null;
 byte c9d;
 byte c80;
 byte c26;
 byte c72;
 byte x,y;
 byte res1, res2;
 byte res;


 conv=hexStringToByteArray(data.substring(0, 2));
 x=conv[0];
 conv=hexStringToByteArray(data.substring(2, 4));
 y=conv[0];
 conv=hexStringToByteArray("9d");
 c9d=conv[0];
 conv=hexStringToByteArray("80");
 c80=conv[0];
 conv=hexStringToByteArray("26");
 c26=conv[0];
 conv=hexStringToByteArray("72");
 c72=conv[0];


 res1=(byte) (c9d ^ x);

 for(int i=1; i<9; i++) 
 {
  if((res1 & c80) == c80)
      res1=(byte) ((res1 << 1) ^ c26);
  else
      res1=(byte) (res1 << 1);
 }

 res2=(byte) (res1 ^ y);
 for(int i=1; i<9; i++) 
 {
  if((res2 & c80) == c80)
      res2=(byte) ((res2 << 1) ^ c72);
  else
      res2=(byte) (res2 << 1);

 }

 res=(byte) ((res1 << 8) | res2);

 return Integer.toHexString(res);
}

たとえば、delphi関数がA877のCABAを返す場合、java関数はFF FFFFBAを返します。

何かご意見は?何か助けはありますか?

ありがとう、ペドロ

4

1 に答える 1

3

この行を見てください:

res=(byte) ((res1 << 8) | res2);

にキャストするとbyte、16 ビットの値が 8 ビットに切り捨てられるため、 が失われres1ます。

2 バイト値にキャストする必要がありますshort

とはいえ、2 バイトを配列で返す方が簡単かもしれません。このような:

public static byte[] MixThingsUp(byte x, byte y)
{
    byte answer1 = (byte) (0x9D ^ x);
    for (int i=0; i<8; i++)
        if ((answer1 & 0x80) == 0x80)
            answer1 = (byte) ((answer1 << 1) ^ 0x26);
        else
            answer1 = (byte) (answer1 << 1);

    byte answer2 = (byte) (answer1 ^ y);
    for (int i=0; i<8; i++)
        if ((answer2 & 0x80) == 0x80)
            answer2 = (byte) ((answer2 << 1) ^ 0x72);
        else
            answer2 = (byte) ((answer2 << 1));

    return new byte[] { answer1, answer2 };
}

私があなたなら、ビット単位の操作と文字列への変換と文字列からの変換を分離します。あなたの質問でのやり方は、2つの懸念を混ぜ合わせています。

于 2013-01-30T10:35:21.823 に答える