string to integer conversion in Pascal, How to do it? - pascal

How to convert a number printed in a string into integer?
Thank you.

The is procedure Val:
procedure Val(S; var V; var Code: Integer);
This procedure operate on decimal and real numbers.
Parmeters:
S char sequence; for proper conversion it has to contain ‘+’, ‘-‘, ‘,’, ’.’, ’0’..’9’.
V The result of conversion. If result going to be an Integer then S can't contain ‘,’, ’.’.
C Return the position of the character from S, that interrupt the conversion.
Use cases:
Var Value :Integer;
Val('1234', Value, Code); // Value = 1234, Code = 0
Val('1.234', Value, Code); // Value = 0, Code = 2
Val('abcd', Value, Code); // Value = 0, Code = 1

You can use Val function.
Example:
var
sNum: String;
iNum: Integer;
code: Integer;
begin
s := '101';
Val(s, iNum, code);
end.

You want Val().

You can use like this,
var
i: integer;
s: string;
begin
str(i, s);
write(i);

Textval := '123';
Val(Textval, Number, Code) ---> Code = 0, Number = 123
Textval := '12345x2';
Val( Textval, Number, Code) ---> Code = 6, Number remains unchanged;
Val( TextVal, Number , Code) which converts String to a number.
if possible the result of code = 0, elese error indication number.

Related

Delphi Function that takes Integer and returns a not-so-easily decoded Integer

Can anyone share what are some common Delphi examples of a function that takes a number
and returns a number that is not so obvious?
For example :
function GetNumber(const aSeed: Integer): Integer;
begin
Result := ((aSeed+5) * aSeed) + 15;
end;
So let's say the user knows that sending aSeed = 21 gives 561
and aSeed = 2, gives 29
and so on...
is there a function that makes it hard to reverse engineer the code,
even if one can generate a large number sets of Seed/Result ?
(hard : I do not mean impossible, just need to be non-trivial)
Preferably a function that does not allow in function result exceeding the
Integer result as well.
In any case, if you are not sure whether it's hard/impossible to reverse,
do feel free to share what you have.
some other requirements:
the same input always results in the same output; cannot have Random output
the same output regardless of platform: windows/android/mac/ios
won't result in some extraordinary big number (fit in Integer)
Using a hash is a very good way to achieve what you want. Here is an example that takes an integer, converts it to a string, appends it to a salt, computes the MD5 and returns the integer corresponding to the first 4 bytes:
uses
System.Hash;
function GetHash(const s: string): TBytes;
var
MD5: THashMD5;
begin
MD5 := THashMD5.Create;
MD5.Update(TEncoding.UTF8.GetBytes(s));
Result := MD5.HashAsBytes;
end;
function GetNumber(Input: Integer): Integer;
var
Hash: TBytes;
p: ^Integer;
begin
Hash := GetHash('secret' + IntToStr(Input));
P := #Hash[0];
Result := Abs(P^);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(GetNumber(1))); // 996659739
ShowMessage(IntToStr(GetNumber(2))); // 939216101
ShowMessage(IntToStr(GetNumber(3))); // 175456750
end;

Not overloading operator

Good day, I'm doing some Codeforces exercises in my free time, and I had a problem to test if the user was a boy or a girl, well, my problem isn't that, i have just demonstrated the code.
While compiling my code in my computer ( I'm using version 3.0.4 for i386 ) i get no error, but codeforces gives me this error
program.pas(15,16) Error: Operator is not overloaded: "freq(Char;AnsiString):LongInt;" + "ShortInt"
program.pas(46,4) Fatal: There were 1 errors compiling module, stopping
The error wasn't clear enough to me, as the same script was perfectly compiled with my version.
The platform is using ( version 3.0.2 i386-Win32 ).
program A236;
uses wincrt, sysutils;
var
username : String;
function freq(char: char; username : String): Integer;
var
i: Integer;
begin
freq:= 0;
for i:= 1 to length(username) do
if char = username[i] then
freq:= freq + 1;
//writeln(freq);
end;
function OddUserName(username : String): Boolean;
var
i, counter: Integer;
begin
OddUserName:= false; // even
counter:= 0;
for i:= 1 to length(username) do
if freq(username[i], username) <> 1 then
delete(username, i, 1)
else
counter:= counter + 1;
if counter mod 2 <> 0 then
OddUserName:= true; // odd
//writeln(counter);
//writeln(OddUserName);
end;
begin
readln(username);
if not OddUserName(username) then
writeln('CHAT WITH HER!')
else
writeln('IGNORE HIM!');
//readkey();
end.
The error is supposed to be at this line probably :
function freq(character: char; username : String): Integer;
Thanks for everyone who helps.
Inside of a function, the function's name can be used as a substitute for using an explicit local variable or Result. freq() and OddUserName() are both doing that, but only freq() is using the function name as an operand on the right-hand side of an assignment. freq := freq + 1; should be a legal statement in modern Pascal compilers, see Why i can use function name in pascal as variable name without definition?.
However, it would seem the error message is suggesting that the failing compiler is treating freq in the statement freg + 1 as a function type and not as a local variable. That would explain why it is complaining about not being able to add a ShortInt with a function type.
So, you will have to use an explicit local variable instead, (or the special Result variable, if your compiler provides that), eg:
function freq(charToFind: char; username : String): Integer;
var
i, f: Integer;
begin
f := 0;
for i := 1 to Length(username) do
if charToFind = username[i] then
f := f + 1;
//writeln(f);
freq := f;
end;
function freq(charToFind: char; username : String): Integer;
var
i: Integer;
begin
Result := 0;
for i := 1 to Length(username) do
if charToFind = username[i] then
Result := Result + 1;
//writeln(f);
end;

Separating numbers in a string. Pascal

I have a problem. I'm learning Pascal for only a couple of weeks and I don't know much. I have to write a program that has to calculate something out of 3 entered numbers. The problem is all 3 of them need to be entered in one edit with spaces in between. So basically I have a string 'number number number'. How do I separate these numbers as 3 separate strings so I can convert them into Integer.
In pascal there are built-in procedures to retrieve the input from the console.
The easiest way to get numeric inputs is to use Read()/ReadLn(), which also can make the conversion from string to a numeric value:
procedure GetNumbers(var x,y,z: Integer);
begin
WriteLn('Enter three numbers separated with space and then press enter.');
ReadLn(x,y,z);
end;
Here, the ReadLn() detects three inputs separated with a space, waits for the [Enter] key and assigns the integer values to the x,y,z variables.
Using the copy function is one way. Sorry about the formatting, I can't understand how to paste code snippets properly in these answer sections.
function TMyForm.Add( anEdit : TEdit ) : integer;
var
Idx : integer;
TempString : string;
function GetNext : integer;
begin
result := result + StrToInt( copy( TempString, 1, Idx - 1 ) );
TempString := copy( TempString, Idx + 1, MAXINT );
end;
begin
result := 0;
TempString := anEdit.Text;
repeat
Idx := pos( ' ', TempString );
if Idx > 0 then
result := GetNext;
until Idx = 0;
if trim( TempString ) <> '' then
//this is the last piece of it then
result := result + StrToInt( trim( TempString ) );
end;
You need to also take care that the values entered are numbers and not letters, usually done with try..except blocks.

Error : Operator is not overloaded

I've created a simple block of code using Free Pascal to validate an ID number such as Abc123 being input.
When I try to run the program I get an error saying, "Operator is not overloaded" at the points where it says,
IF not (Ucase in Upper) or (Lcase in Lower) or (Num in Int) then
Specifically where the "in" appears.
Does anyone have any idea why the error occurs and what I can do to solve it?
Thanks!
Program CheckChar;
VAR
UserID, LCase, UCase, Num : String;
readkey : char;
L : Integer;
CONST
Upper = ['A'..'Z'];
Lower = ['a'..'z'];
Int = ['0'..'9'];
Begin
Write('Enter UserID ');Readln(UserID);
Ucase := Copy(UserID,1,1);
LCase := Copy(UserID,2,1);
Num := Copy(UserID,3,2);
L := Length(UserID);
While L = 6 Do
Begin
IF not (Ucase in Upper) or (Lcase in Lower) or (Num in Int) then
Begin
Writeln('Invalid Input');
End;
Else
Writeln('Input is valid');
End;
readln(readkey);
End.
in is used to test the presence of an element in a set. Here you set is a set of char, so the element to test must also be a char. In your sample the elements you tested were some strings (UCase, LCase and Num) which caused the error message.
You have to use a slice of Ucase and LCase of length one or you can also directly take a single character (astring[index]) instead of copying with Copy.
Also your while loop is totally useless. You have to test only 6 characters so let's unroll the loop instead of puting some complexity while obsvioulsy you just start learning.
Finally, one way to write your checker correctly is so:
Program CheckChar;
var
UserID : string;
readkey : char;
L : Integer;
invalid: boolean;
const
Upper = ['A'..'Z'];
Lower = ['a'..'z'];
Int = ['0'..'9'];
begin
Write('Enter UserID ');
Readln(UserID);
L := length(UserId);
if L <> 6 then invalid := true
else
begin
invalid := not (UserID[1] in Upper) or // take a single char, usable with in
not (UserID[2] in Lower) or // ditto
not (UserID[3] in Lower) or // ditto
not (UserID[4] in Int) or // ditto
not (UserID[5] in Int) or // ditto
not (UserID[6] in Int); // ditto
end;
if invalid then
Writeln('Invalid Input')
else
Writeln('Input is valid');
readln(readkey);
end.

How to convert integer to array of bytes?

I have sort of action listener in ST code (similar to Pascal), where it returns me an integer. Then i have a CANopen function, which allows me to send data only in Array of bytes. How can i convert from these types?
Thanks for answer.
You can use the Move standard function to block-copy the integer into an array of four bytes:
var
MyInteger: Integer;
MyArray: array [0..3] of Byte;
begin
// Move the integer into the array
Move(MyInteger, MyArray, 4);
// This may be subject to endianness, use SwapEndian (and related) as needed
// To get the integer back from the array
Move(MyArray, MyInteger, 4);
end;
PS: I haven't coded in Pascal for a few months now so there might be mistakes, feel free to fix.
Here are solutions working with Free Pascal.
First, with "absolute":
var x: longint;
a: array[1..4] of byte absolute x;
begin
x := 12345678;
writeln(a[1], ' ', a[2], ' ', a[3], ' ', a[4])
end.
With pointers:
type tarray = array[1..4] of byte;
parray = ^tarray;
var x: longint;
p: parray;
begin
x := 12345678;
p := parray(#x);
writeln(p^[1], ' ', p^[2], ' ', p^[3], ' ', p^[4])
end.
With binary operators:
var x: longint;
begin
x := 12345678;
writeln(x and $ff, ' ', (x shr 8) and $ff, ' ',
(x shr 16) and $ff, ' ', (x shr 24) and $ff)
end.
With record:
type rec = record
case kind: boolean of
true: (int: longint);
false: (arr: array[1..4] of byte)
end;
var x: rec;
begin
x.int := 12345678;
writeln(x.arr[1], ' ', x.arr[2], ' ', x.arr[3], ' ', x.arr[4])
end.
You can also use a variant record, which is the traditional method of deliberately aliasing variables in Pascal without using pointers.
type Tselect = (selectBytes, selectInt);
type bytesInt = record
case Tselect of
selectBytes: (B : array[0..3] of byte);
selectInt: (I : word);
end; {record}
var myBytesInt : bytesInt;
The nice thing about the variant record is that, once you set it up, you can freely access the variable in either form without having to call any conversion routines. For example "myBytesInt.I:=$1234" if you want to access it as an integer, or "myBytesInt.B[0]:=4" etc if you want you access it as a byte array.
You can do something like this :
byte array[4];
int source;
array[0] = source & 0xFF000000;
array[1] = source & 0x00FF0000;
array[2] = source & 0x0000FF00;
array[3] = source & 0x000000FF;
Then if you glue array[1] to array[4] together you will get your source integer;
Edit : corrected the mask.
Edit : As Thomas pointed out in the comments -> you still have to bit shift the resulting value of ANDing to LSB to get correct values.

Resources