troubleshooting Question

# How to convert a string or a character to its binary representation

DelphiAssembly
Hi all. This is the chapter 2 of "The incredible adventures of my brain against Assembly language". For learning and training purposes, I'm writeing a small app to help me to memorize conversion table between binary and hexadecinal. Or better, this was at first. The project has grown up and has became more complex. Now I wrote a little piece of code to convert Integer to Binary and viceversa. I found the first function over the Internet and I have just extended it a little:

``````//pad values with zeros to obtain a final string multiple of 4 - regular nibbles
function TForm1.FillNibbles(s: string): string;
var
r: Integer;
begin
Result := s;
r := Length(s) mod 4;
if r <> 0 then
begin
if r = 25 then
Result := '000' + s
else if r = 50 then
Result := '00' + s
else
Result := '0' + s;
end;
end;

//divides string in groupof 4 chars (nibbles separating them by a white space
var
i, counter: Integer;
begin
Result := '';
counter := 1;
for i := Length(s) downto 1 do
begin
if counter < 4 then
begin
Result := s[i] + Result;
Inc(counter);
end
else
begin
Result := s[i] + Result;
if i > 1 then
Result := ' '+ Result;
counter := 1;
end;
end;
end;

// Convert an integer to its binary representation using division by 2 method
function TForm1.MyIntToBin(n: LongInt; Fill: Boolean = True; Readable: Boolean = True): string;
var
t, r: Integer;
s: string;
begin
s := '';
t := n;
repeat
if (t mod 2) = 0 then
s := '0' + s
else
s := '1' + s;
t := t div 2;
until t = 0;
if Fill then
s := FillNibbles(s);
Result := s;
end;
``````

Here is the my self-written function to convert from binary to Integer:

``````function TForm1.MyBinToInt(v: string): LongInt;
var
i, r, p: Integer;
begin
Result := 0;
p := 0;
for i := Length(Trim(v)) downto 1 do
begin
r := Round(StrToInt(v[i]) * Power(2, p));
Inc(p);
Result := Result + r ;
end;
end;
``````

Well. Now I would like to understand how I can convert a normal text string to Binary: What is the correct method? I have to take the Integer value of each single char using the ASCII tableand then apply the same method used for numbers? Or there is some other technique?

Thanks to all.
Join the community to see this answer!
###### Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.