我目前有两个函数是实现此功能的,但只能处理正整数,负整数会出错,能否帮我增加处理负整数功能呢?谢谢!!!
//将整数转换为协议整数 - 按网络字节顺序的多个字节
Function ConvertInteger (Source,Len : Integer) : String;
Var
    i               : Integer;
Begin
    Result := '';
    For i := 1 To Len Do
    Begin
        Result := Chr (Source And $FF) +Result;
        Source := Source Shr 8;
    End;
End;
//将协议整数(网络字节顺序的多个字节)还原为整数
Function RevertInteger (Source : String) : Integer;
Var
    i               : Integer;
Begin
    Source := Copy (Source,1,4) ;
    Result := 0;i := 1;
    While i<=Length (Source) Do
    Begin
        Result := Result Shl 8+Ord (Source[i]) ;
        Inc (i) ;
    End;
End;

解决方案 »

  1.   

    将-2代进去,返回时成254了。测试代码如下:
    Procedure TForm1.Button8Click (Sender : TObject) ;
    Var
        EE,EE2          : Integer;
        str             : String;
    Begin
        EE := -2;
        EE2 := 0;
        str := ConvertInteger (EE,1) ;
        EE2 := RevertInteger (str) ;
        showmessage ('EE2='+IntToStr (EE2) ) ;
    End;
      

  2.   

    function ConvertInteger(Source, Len: Integer): String;
    var
      i: Integer;
    begin
      Result := '';
      if Len > SizeOf(Source) then
        Exit;
      for i := 1 to Len do
      begin
        Result := Chr(Source and $FF) + Result;
        Source := Source shr 8;
      end;
    end;
    //将协议整数(网络字节顺序的多个字节)还原为整数
    function RevertInteger(Source: String): Integer;
    var
      i, Len: Integer;
      n: Int64;
    begin
      Source := Copy(Source, 1, SizeOf(Result));
      Result := 0;
      n := 0;
      i := 1;
      Len := Length(Source);
      while i <= Length(Source) do
      begin
        n := n shl 8 + Ord(Source[i]);
        Inc(i);
      end;
      if n > Power($100, Len) / 2 - 1 then
        n := n - Floor(Power($100, Len));
      Result := n;
    end;//LZ要这个干嘛???这样转换很容易出界的