将delphi二进制操作函数移植到java

时间:2013-01-30 10:26:04

标签: java delphi porting

让我开始说我对Delphi一无所知......

我正在尝试将用delphi编写的旧应用程序移植到java中,但是事情不起作用......

我有这个函数对两个字节进行一些二进制操作。这是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函数返回A BA 77的CA BA时,java函数返回FF FF FF BA

有什么想法?有什么帮助吗?

谢谢, 佩德罗

1 个答案:

答案 0 :(得分:3)

看看这一行:

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

当您将其转换为byte时,您将16位值截断为8位,因此丢失res1

您应该转换为2字节值short

也就是说,在数组中返回两个字节可能更容易。像这样:

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 };
}

如果我是你,我会将按位操作和转换与字符串分开。你在问题中的方式混合了两个问题。