Gallery
Software
Music
Programming
Archive
Wednesday, Apr 24 Week 17
Two examples of converting ANSI text into numbers.
Using of the functions requires that the text is actually a number, and that it fits into a byte/word.
The examples is faster if the length is known.

function strToByte(p:pAnsiChar;n:byte):byte;
begin case n of
1:result:=pByte(p)^-48;
2:result:=((pByte(p)^-48)*10)+pByte(p+1)^-48;
3:result:=((pByte(p)^-48)*100)+((pByte(p+1)^-48)*10)+pByte(p+2)^-48
else result:=0 end
end;

function strToWord(p:pAnsiChar;n:byte):word;
begin case n of
1:result:=pByte(p)^-48;
2:result:=((pByte(p)^-48)*10)+ pByte(p+1)^-48;
3:result:=((pByte(p)^-48)*100)+((pByte(p+1)^-48)*10)+pByte(p+2)^-48;
4:result:=((pByte(p)^-48)*1000)+((pByte(p+1)^-48)*100)+((pByte(p+2)^-48)*10)+pByte(p+3)^-48;
5:result:=((pByte(p)^-48)*10000)+((pByte(p+1)^-48)*1000)+((pByte(p+2)^-48)*100)+((pByte(p+3)^-48)*10)+pByte(p+4)^-48;
else result:=0 end
end;

Example

procedure TForm1.FormCreate(Sender: TObject);
var s:string;k:word;
begin
s:='65535';
k:=strToWord(pAnsiChar(s),length(s));
caption:=intToStr(k);
end;

Related pages of Fast StrToByte and StrToWord

Bytes and data-types
Delphi examples
Delphi programming
Programming