Is it Possible to convert a set of numbers to their ASCII Char values?

1.8k views Asked by At

I can convert a string into the Ascii values with spaces in between.

Example: "I like carrots" To: 73 32 108 105...

But I'm trying to figure out a way to take those NUMBERS and convert them BACK into their ascii Chars.

I'm using the latest version of Delphi (embarcadero) and am new to coding so pls help me out :)

3

There are 3 answers

2
javierj On

You can use the Ord function in every character. The Chr function returns the character for specified ASCII value.

Example

var
  s: string;
  c: char;

s:='I like carrots';
for c in s do
begin
   Writeln(ord(c));
end;
1
Art Bacon On

I don't know much about delphi, but take a look at this link: http://www.delphibasics.co.uk/Article.asp?Name=Text

In the Assigning to and from character variables section it demonstrates a function like so: fromNum := Chr(65); // Assign using a function.

If that doesn't work, you could consider building a large mapping of int->char. The beginnings of which is in that above website also near the top.

5
fpiette On

Here is the code:

var
    S1 : String;
    S2 : String;
    A  : TStringDynArray;   // Add System.Types in uses
    N  : String;
    C  : Char;
begin
    // 'I like carrots' in ascii code separated by a space
    S1 := '73 32 108 105 107 101 32 99 97 114 114 111 116 115';
    A  := SplitString(S1, ' ');   // Add System.StrUtils in uses
    S2 := '';
    for N in A do
        S2 := S2 + Char(StrToInt(N));
    ShowMessage(S2);
end;

I don't know the complete problem but you could add code to check of valid input string.