Domanda

I want to convert a String to a byte array, the code looks like the following:

procedure StringToByteArray(const s : String; var tmp: array of Byte);
var
  i : integer;
begin
       For i:=1 to Length(s) do
       begin
            tmp[i-1] := Ord(s[i]);
       end;

end;

s[i] here is the i'th String element (= char at pos i) and I'm saving its numerical value to tmp.

This works for some characters, but not for all, for example:

Ord('•') returns Dec(149), which is what I expect.

But in my procedure Ord(s[i]) returns Dec(8226) for the same character!

Edit1: I think the defect lies in my other function "ByteArrayToStr"

When converting ...

tmp:= 149    // tmp is of type byte
Log('experiment: ' + Chr(tmp));  // prints "•"
Log('experiment2 ' + IntToStr(Ord(Chr(tmp)))); // prints 149

... back and forth, this seems to work.

But using the same conversion in the following function won't do it:

function ByteArrayToStr( a : array of Byte ) : String;
var
  S:String;
  I:integer;
begin
     S:='';
     For I:=0 to Length(a) -1 do
     begin
          tmp := Chr(a[I]) ;   // for a[I] equals 149 this will get me "?" instead of "•"
          S:=S+tmp;

     end;

     Result:=S;
end;

To make it clear: ByteArrayToStr does not convert Ord(149) to "•" as expected, and therefore StringToByteArray won't work later on

È stato utile?

Soluzione

You need to turn your parameters into AnsiString type. By doing so, you can write functions like this:

[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
OutputDir=userdocs:Inno Setup Examples Output

[Code]
procedure StringToByteArray(const S: AnsiString; out ByteArray: array of Byte);
var
  I: Integer;
begin
  SetArrayLength(ByteArray, Length(S));
  for I := 1 to Length(S) do
    ByteArray[I - 1] := Ord(S[I]);
end;

function ByteArrayToString(const ByteArray: array of Byte): AnsiString;
var
  I: Integer;
begin
  SetLength(Result, GetArrayLength(ByteArray));
  for I := 1 to GetArrayLength(ByteArray) do
    Result[I] := Chr(ByteArray[I - 1]);
end;

procedure InitializeWizard;
var
  S: AnsiString;
  ByteArray: array of Byte;
begin
  S := '•';
  StringToByteArray(S, ByteArray);
  MsgBox(IntToStr(ByteArray[0]), mbInformation, MB_OK);
  S := '';
  S := ByteArrayToString(ByteArray);
  MsgBox(S, mbInformation, MB_OK);
end;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top