Lazarus

Free Pascal => General => Topic started by: Seenkao on January 10, 2022, 02:33:39 pm

Title: StrToInt in pure pascal.
Post by: Seenkao on January 10, 2022, 02:33:39 pm
Rus:
Всем привет!

Я доделал функцию StrToInt, как оказалось, она имела определённые ошибки, которые выявились в процессе общения в соседних топиках. Можно поблагодарить людей, которые помогли мне (сами того не зная).  ;)

Было бы неплохо, если бы вы проверили её на работоспособность.
-->fast_StrToInt скачать (https://github.com/Seenkao/fast_StrToInt.git)<-- ;)

Зачем я это сделал? Функция быстрее работает на процессорах x86 чуть менее чем в два раза, на процессорах ARM быстрее, но я не помню насколько. А так как зачастую в программах используется перевод строковых значений в числа, то я думаю это немалый прирост в скорости.

Обратите внимание! Данная библиотека рассчитана на скорость перевода строки в число! А так же на совместимость с разными архитектурами. :) Но обрабатывает она только числа, знак "-" (минус) и префиксы для шестнадцатеричной, восмеричной и двоичной систем. Все остальные символы будут игнорированы и в этом случае все функции будут выдавать не верный результат (даже если вы просто поставите пробел перед числом).

плюсы (+): быстрее скорость работы, сделано на чистом паскале, подойдёт для любой платформы и архитектуры (по крайней мере должны). Функция не вылетит с ошибкой! Результат функции булева переменная сообщающая успешен был перевод или нет, сам результат в Value. Функция позволяет выбирать размерность обрабатываемых данных.

минусы (-): просьба собщить о минусах функций. Я их создавал. Потому мой взгляд однобокий.

примеры использования в программе. Сама функция geStrToInt в соседнем модуле. Пример сделан для разных систем Linux/Windows (возможно и MacOS но не совсем уверен в дефайнах).

Модуль предоставляет 16 пользовательских функций, основанных на трёх основных:
Code: Pascal  [Select][+][-]
  1. (* Rus: Ниже реализованы стандартные функции для перевода строк в число. Их
  2.  *      использование будет проще для большинства. Функции отмечены префиксом.
  3.  *      s_ - функции возвращают результат (если операция была неудачной, то
  4.  *      в результате вернётся ноль, но вы не узнаете, что операция была неудачной).
  5.  *      sc_ - результат функций удачная или не удачная была операция. Сам
  6.  *      конечный числовой результат считывайте в Value.
  7.  *)
  8.  
  9. // Rus: Числа со знаком. Здесь нельзя использовать шестнадцатеричные, восьмеричные
  10. //      и двоичные числа.
  11. function sc_StrToShortInt(const Str: String; out Value: ShortInt): Boolean;    // byte
  12. function s_StrToShortInt(const Str: String): ShortInt;                         // byte
  13. function sc_StrToSmallInt(const Str: String; out Value: SmallInt): Boolean;    // word
  14. function s_StrToSmallInt(const Str: String): SmallInt;                         // word
  15. function sc_StrToInt(const Str: String; out Value: Integer): Boolean;
  16. function s_StrToInt(const Str: String): Integer;
  17. function sc_StrToInt64(const Str: String; out Value: Int64): Boolean;
  18. function s_StrToInt64(const Str: String): Int64;
  19.  
  20. // Rus: Числа без знака. Эти функции могут использоваться и для шестнадцатеричныи
  21. //      и восьмеричных и двоичных чисел. Данные функции не должны содержать
  22. //      ведущие нули для десятеричной системы счисления.
  23. function sc_StrToByte(const Str: String; out Value: Byte): Boolean;
  24. function s_StrToByte(const Str: String): Byte;
  25. function sc_StrToWord(const Str: String; out Value: Word): Boolean;
  26. function s_StrToWord(const Str: String): Word;
  27. function sc_StrToLongWord(const Str: String; out Value: LongWord): Boolean;
  28. function s_StrToLongWord(const Str: String): LongWord;
  29. function sc_StrToQWord(const Str: String; out Value: QWord): Boolean;
  30. function s_StrToQWord(const Str: String): QWord;  

Модуль предоставляет три основных функции:
Code: Pascal  [Select][+][-]
  1. function geStrToInt(const Str: String; out Value: maxIntVal; Size: LongWord = isInteger): Boolean; // для десятичных чисел со знаком.
  2. function geStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isLongWord): Boolean; // для десятичных чисел без знака.
  3. function geHOBStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isQWord): Boolean; // для работы с шестнадцатеричными, восьмеричными и двоичными значениями.


Внимание!!! при использовании данного модуля, не включайте в отладчике флаг переполнения! Это может вызвать у вас ошибку переполнения при исполнении вашей программы.
Модуль использует способ переполнения для более быстрой обработки чисел.
- надо тестировать. На данное время проблема решена (но протестировано только мной).

При работе с шестнадцатеричными, восьмеричными и двоичными данными, вы будете работать только с без знаковыми числами UInt.
Я не считаю, что данные числа должны быть знаковыми (по моему и неудобно). Потому, если вам это необходимо, то вы сами можете доделать те функции, которые вам необходимы.

Шестнадцатеричные можно объявлять: '$', '0x' или '0X'.
Восьмеричные можно объявлять: '&' или '0' (не видел больше ни каких объявлений, если не прав, поправьте меня).
Двоичные можно объявлять: '%', '0b' или '0B'.

Тестируйте, сообщайте об ошибках. Буду править если что сделал не так. :-[

-----------------------------------------
Eng:

Hello everyone!

I completed the StrToInt function, as it turned out, it had certain errors that were revealed in the process of communication in neighboring topics. You can thank the people who helped me (without knowing it). ;)

It would be nice if you could test it to see if it works.
-->fast_StrToInt download. (https://github.com/Seenkao/fast_StrToInt.git)<-- ;)

Why did I do this? The function works a little less than twice as fast on x86 processors, and faster on ARM processors, but I don't remember how much. And since the translation of string values ​​into numbers is often used in programs, I think this is a considerable increase in speed.

Note! This library is aimed at the speed of translating strings into numbers! As well as compatibility with different architectures. :) But it only handles numbers, "-" sign (minus) and prefixes for hexadecimal, octal and binary systems. All other characters will be ignored, in which case all functions will give incorrect results (even if you just put a space before the number).

pluses (+): faster speed, made on pure pascal, suitable for any platform and architecture (at least they should). The function will not crash! The result of the function is a boolean variable reporting success or not, the result itself is in Value. The function allows you to select the dimension of the processed data.

cons (-): please report the cons of the functions. I created them. My view is one sided.

examples of use in the program. The function geStrToInt itself is in the neighboring module. The example is made for different Linux / Windows systems (possibly MacOS, but I'm not quite sure about the defines).

The module provides 16 custom functions based on three main ones:
Code: Pascal  [Select][+][-]
  1. (*
  2.  * Eng: The standard functions for converting strings to numbers are implemented
  3.  *      below. Their use will be easier for most. Functions are marked with a prefix.
  4.  *      s_ - functions return a result (if the operation was unsuccessful, the result
  5.  *      will be zero, but you will not know that the operation was unsuccessful).
  6.  *      sc_ - the result of the functions - the operation was successful or
  7.  *      unsuccessful. Read the final numerical result in Value.
  8.  *)
  9.  
  10. // Eng: Signed numbers. Hexadecimal, octal and binary numbers cannot be used here.
  11. function sc_StrToShortInt(const Str: String; out Value: ShortInt): Boolean;    // byte
  12. function s_StrToShortInt(const Str: String): ShortInt;                         // byte
  13. function sc_StrToSmallInt(const Str: String; out Value: SmallInt): Boolean;    // word
  14. function s_StrToSmallInt(const Str: String): SmallInt;                         // word
  15. function sc_StrToInt(const Str: String; out Value: Integer): Boolean;
  16. function s_StrToInt(const Str: String): Integer;
  17. function sc_StrToInt64(const Str: String; out Value: Int64): Boolean;
  18. function s_StrToInt64(const Str: String): Int64;
  19.  
  20. // Eng: Numbers without a sign. These functions can be used for hexadecimal, octal
  21. //      and binary numbers as well. These functions must not contain leading zeros
  22. //      for the decimal number system.
  23. function sc_StrToByte(const Str: String; out Value: Byte): Boolean;
  24. function s_StrToByte(const Str: String): Byte;
  25. function sc_StrToWord(const Str: String; out Value: Word): Boolean;
  26. function s_StrToWord(const Str: String): Word;
  27. function sc_StrToLongWord(const Str: String; out Value: LongWord): Boolean;
  28. function s_StrToLongWord(const Str: String): LongWord;
  29. function sc_StrToQWord(const Str: String; out Value: QWord): Boolean;
  30. function s_StrToQWord(const Str: String): QWord;  

The module provides three main functions:
Code: Pascal  [Select][+][-]
  1. function geStrToInt(const Str: String; out Value: maxIntVal; Size: LongWord = isInteger): Boolean; // for signed decimal numbers.
  2. function geStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isLongWord): Boolean; // for unsigned decimal numbers.
  3. function geHOBStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isQWord): Boolean; // for working with hexadecimal, octal and binary values.

Attention!!! When using this module, do not enable the overflow flag in the debugger! This can give you an overflow error when you run your program.
The module uses an overflow method for faster processing of numbers.
- need to be tested. At this time, the problem is solved (but only tested by me).

When working with hexadecimal, octal, and binary data, you will only be working with unsigned UInts.
I do not believe that these numbers should be signed numbers (in my opinion, and inconveniently). Therefore, if you need it, then you yourself can complete the functions that you need.

Hexadecimal can be declared: '$', '0x' or '0X'.
Octal can be declared: '&' or '0' (didn't see any other declarations, if wrong, correct me).
Binary can be declared: '%', '0b' or '0B'.

Test, report bugs. I will correct if I did something wrong.  :-[
Title: Re: StrToInt in pure pascal.
Post by: AlexTP on January 10, 2022, 04:30:10 pm
AFAIK the usual StrToInt is based on Val().
So better rewrite Val(), not StrToInt / StrToDWord / StrToQWord / StrToByte / StrToInt64.
It will be not simple for you.
Because Val also supports hex/octal/bin formats.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 10, 2022, 04:56:27 pm
AFAIK the usual StrToInt is based on Val().
So better rewrite Val(), not StrToInt / StrToDWord / StrToQWord / StrToByte.
Функция Val достаточно давно создана и по моему мнению достаточно большая часть из неё устарела, потому что от Val требовали достаточно многого. Функция достаточно универсальна, но делалась в стародавние времена и я не уверен что кто-то за неё вообще брался за это время (могу ошибаться).

google translate:
The Val function was created a long time ago, and in my opinion, a fairly large part of it is outdated, because quite a lot was demanded from Val. The function is quite versatile, but it was made in ancient times and I'm not sure that anyone at all took it on during this time (I could be wrong).

Quote
It will be not simple for you.
Почему вы за меня что-то решаете?  :) На самом деле разные форматы добавить намного проще, чем создать функцию основу StrToInt. При чём, вы забываете, что многое сделано до меня, я лишь это всё собрал и оптимизировал.

google translate:
Why are you deciding something for me? :) In fact, it is much easier to add different formats than to create a base function StrToInt. Moreover, you forget that a lot has been done before me, I just collected and optimized it all.

Quote
Because Val also supports hex/octal/bin formats.
да, да, а так же перевод чисел с плавающей запятой.
Хотите я могу предоставить вам эту возможность?  :)

google translate:
yes, yes, as well as translation of floating point numbers.
Do you want me to give you this opportunity? :)
Title: Re: StrToInt in pure pascal.
Post by: engkin on January 10, 2022, 05:26:00 pm
Thanks for sharing. Just a quick note, instead of:
Code: Pascal  [Select][+][-]
  1.     {$If defined(CPUX86_64) or defined(aarch64)}

use:
Code: Pascal  [Select][+][-]
  1.     {$ifdef CPU64}
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 10, 2022, 05:39:41 pm
use:
Code: Pascal  [Select][+][-]
  1.     {$ifdef CPU64}
Благодарю! Я был в сомнениях какие дефайны правильно использовать. А где можно посмотреть более подробную информацию по defines?

google translate:
Thanks to! I was in doubt which defines to use correctly. And where can I see more detailed information on defines?

А по переводу шестнадцатеричных/восьмеричных/двоичных чисел возникает закономерный вопрос, а знак "-" там вообще должен участвовать?
Я, как человек начинавший работать с ассемблером, рассматриваю подобные числа не относящимся к числам со знаком, а просто как числовое значение в данном формате.

google translate:
And on the translation of hexadecimal/octal/binary numbers, a natural question arises, and should the "-" sign participate there at all?
As a person who started working with assembler, I consider such numbers not related to signed numbers, but simply as a numerical value in this format.
Title: Re: StrToInt in pure pascal.
Post by: AlexTP on January 10, 2022, 05:59:48 pm
List of defines:
https://wiki.freepascal.org/Platform_defines
Title: Re: StrToInt in pure pascal.
Post by: engkin on January 10, 2022, 06:11:10 pm
And on the translation of hexadecimal/octal/binary numbers, a natural question arises, and should the "-" sign participate there at all?

I don't think so, for one where would the sign go? -$A5 or $-A5
Title: Re: StrToInt in pure pascal.
Post by: AlexTP on January 10, 2022, 07:00:18 pm
Quote
and should the "-" sign participate there at all?

FPC tokenizes leading '-' as additional operator (unary or binary). So FPC does the calculations. So you must not allow '-'.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 10, 2022, 07:20:38 pm
Thanks for the information! ;)
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 10, 2022, 07:57:24 pm
забыл... в function geStrToInt(Str: String; Size: LongWord = isInteger): Boolean; - надо указать как константу строку...
function geStrToInt(const Str: String; Size: LongWord = isInteger): Boolean; - в таком варианте. Это добавляет ещё скорости работы.
Пойду исправлю в исходниках.

google translate:
forgot ... in function geStrToInt (Str: String; Size: LongWord = isInteger): Boolean; - you must specify a string as a constant ...
function geStrToInt (const Str: String; Size: LongWord = isInteger): Boolean; - in this case. This adds even more speed to the work.
I'll go fix it in the source.
Title: Re: StrToInt in pure pascal.
Post by: Bart on January 10, 2022, 09:27:18 pm
And on the translation of hexadecimal/octal/binary numbers, a natural question arises, and should the "-" sign participate there at all?

I don't think so, for one where would the sign go? -$A5 or $-A5

-$A5.
Val() happily accepts that (for signed integers).
-$A5 just means the negative of $A5.
The simple fact that the notation is in hex format does not mean the value cannot be negative.

Bart
Title: Re: StrToInt in pure pascal.
Post by: PascalDragon on January 11, 2022, 10:08:10 am
google translate:
The Val function was created a long time ago, and in my opinion, a fairly large part of it is outdated, because quite a lot was demanded from Val. The function is quite versatile, but it was made in ancient times and I'm not sure that anyone at all took it on during this time (I could be wrong).

You are wrong. As Val is the base function for essentially all conversions from a string to an integer or floating point number it's quite often adjusted and fixed (especially considering that it's used by the compiler itself). The most recent changes were just a few hours ago (https://gitlab.com/freepascal.org/fpc/source/-/commit/beecbf1581a986f544fde77aa428e05c21a35f6f) due to some problems encountered there (https://gitlab.com/freepascal.org/fpc/source/-/issues/39406) and its performance is under review as well. So to say that it's outdated is absolutely wrong.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 11, 2022, 12:29:38 pm
The most recent changes were just a few hours ago (https://gitlab.com/freepascal.org/fpc/source/-/commit/beecbf1581a986f544fde77aa428e05c21a35f6f) due to some problems encountered there (https://gitlab.com/freepascal.org/fpc/source/-/issues/39406) and its performance is under review as well. So to say that it's outdated is absolutely wrong.
Я предоставил на обозрение код, который в два с лишним раза обходит по скорости рабочий код функции Val и сделан на чистом паскале (а значит подойдёт для любой платформы). Почему я не могу утверждать, что код функции Val не устарел?
Желательно указывать не недавние изменения, а изменения, которые были произведены хотя бы год-два назад, тогда это будет более конкретным подтверждением, что над функцией Val работают. :)

Я посмотрел "изменённый" код на скорую руку
Code: Pascal  [Select][+][-]
  1. base,u : byte;
  2. ...
  3. base,len,baseindex : byte;
  4.  
байты? Серьёзно? На 32-х, 64-х битных системах?
Вопрос почему? Чтоб компилятор ещё добавочно тратил расходы на перевод чисел?

Не рассматривайте это с плохой стороны. Я всегда смотрю со своей стороны и могу ошибаться! И говорю прямо, то что вижу. Надеюсь на понимание. И благодарю за предоставленную информацию! :)

google translate:
I have provided for review a code that bypasses the working code of the Val function more than twice in speed and is made in pure Pascal (which means it is suitable for any platform). Why can't I argue that the Val function code is not out of date?
It is advisable to indicate not recent changes, but changes that were made at least a year or two ago, then this will be a more specific confirmation that the Val function is being worked on. :)

I looked at the "changed" code in a hurry
Code: Pascal  [Select][+][-]
  1.  base, u: byte;
  2. ...
  3. base, len, baseindex: byte;
  4.  
bytes? Seriously? On 32-bit, 64-bit systems?
The question is why? So that the compiler additionally spent the cost of translating numbers?

Don't take it badly. I always look from my side and I can be wrong! And I say directly what I see. Hope for understanding. And thank you for the information provided! :)
Title: Re: StrToInt in pure pascal.
Post by: PascalDragon on January 11, 2022, 01:39:29 pm
google translate:
I have provided for review a code that bypasses the working code of the Val function more than twice in speed and is made in pure Pascal (which means it is suitable for any platform). Why can't I argue that the Val function code is not out of date?

If it would be "out of date" it wouldn't be worked on.

It is advisable to indicate not recent changes, but changes that were made at least a year or two ago, then this will be a more specific confirmation that the Val function is being worked on. :)

What difference does it make whether it was two days ago or a year? A bug was found and that bug is fixed now.

I looked at the "changed" code in a hurry
Code: Pascal  [Select][+][-]
  1.  base, u: byte;
  2. ...
  3. base, len, baseindex: byte;
  4.  
bytes? Seriously? On 32-bit, 64-bit systems?
The question is why? So that the compiler additionally spent the cost of translating numbers?

Any why use larger values? There is simply no need. Using smaller types results in less stack space used which is essentially important on low-end systems. Don't forget that FPC also supports systems like i8086, Z80 and AVR which are grateful for every Byte that is available for other purposes. And we don't want to maintain even more implementations than we already have (in fact the hope is to reduce the number of different Val implementations even more to reduce the maintenance burden).
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 11, 2022, 02:24:25 pm
If it would be "out of date" it wouldn't be worked on.
Над ним и не работают. Не надо делать вид, что поломка - это работа над улучшением функции! Это восстановление рабочих параметров функции и вернее всего из-за того, что хотели что-то исправить в параллельных данных.
google translate:
They are not working on it. Don't pretend that the breakdown is due to an improvement in function! This is the restoration of the working parameters of the function and most likely due to the fact that they wanted to fix something in parallel data.

Quote
What difference does it make whether it was two days ago or a year? A bug was found and that bug is fixed now.
ещё раз повторюсь, большая. Не надо рассказывать что поломка и улучшение - это одно и то же. Поломка - это когда надо восстановить работоспособность. Улучшение - это изменение функции для улучшения её работоспособности и ускорения скорости её работы, а так же по возможности исключения возникновения ошибок при её работе.
google translate:
I repeat, big. No need to say that breakdown and improvement are one and the same. Breakdown is when it is necessary to restore performance. Improvement is a change in a function to improve its performance and speed up its operation, as well as, if possible, eliminate the occurrence of errors during its operation.

Quote
Any why use larger values? There is simply no need. Using smaller types results in less stack space used which is essentially important on low-end systems. Don't forget that FPC also supports systems like i8086, Z80 and AVR which are grateful for every Byte that is available for other purposes. And we don't want to maintain even more implementations than we already have (in fact the hope is to reduce the number of different Val implementations even more to reduce the maintenance burden).
Есть причины использовать как минимум способы для подбора величины под компилируемую систему (например "define").
google translate:
There are reasons to use at least methods for choosing the value for the compiled system (for example, "define").

P.S. У меня складывается однозначное мнение, что вы против развития паскаля. В одном топике вы мне отвечаете одно, в другом другое... Я очень надеюсь что я ошибаюсь!!!
google translate:
P.S. I have an unambiguous opinion that you are against the development of Pascal. In one topic you answer me one thing, in another another ... I really hope that I'm wrong !!!
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 11, 2022, 02:34:46 pm
Большая просьба больше не флудить не по теме в данном топике, есть желание, давайте создадим другой топик и пообщаемся там. Или пишите мне в личку.

Здесь я показываю пример функции подобной StrToInt работающей быстрее, без ошибок и на чистом паскале (а это означает, что подойдёт для любой системы). Я буду рад, если будут какие-то предложения по её улучшению.
А я в свою очередь добавлю возможность её работы для других систем счислений.

google translate:
A big request not to flood any more off-topic in this topic, there is a desire, let's create another topic and talk there. Or write to me in a personal.

Here I show an example of a function like StrToInt that works faster, without errors and in pure pascal (which means that it will work for any system). I will be glad if there are any suggestions for improving it.
And I, in turn, will add the possibility of its work for other number systems.
Title: Re: StrToInt in pure pascal.
Post by: Bart on January 11, 2022, 03:31:18 pm
In the bugtracker thread about this, Isopod posted already faster algorithms for Val.

Bart
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 11, 2022, 03:50:08 pm
Благодарю за информацию!
Где её можно посмотреть?

google translate:
Thank you for the information!
Where can you watch it? :-[
Title: Re: StrToInt in pure pascal.
Post by: AlexTP on January 11, 2022, 04:22:53 pm
This commit
https://gitlab.com/freepascal.org/fpc/source/-/commit/beecbf1581a986f544fde77aa428e05c21a35f6f
Title: Re: StrToInt in pure pascal.
Post by: Bart on January 11, 2022, 04:33:26 pm
This commit
https://gitlab.com/freepascal.org/fpc/source/-/commit/beecbf1581a986f544fde77aa428e05c21a35f6f

That one fixes Val() for signed integers (and speeds it up a little).

Here (https://gitlab.com/Isopod/fpcval) is the implementation proposal of Isopod.

See the extended discussion in this bugtracker issue (https://gitlab.com/freepascal.org/fpc/source/-/issues/39406).

Val() for unsigend integers is still broken though (it always expects the return value to be 32 or 64-bit, so it generates range check errors if you do Val('999',ByteVariable,Code), instead of just setting Code to 3 in this case).

Bart
Title: Re: StrToInt in pure pascal.
Post by: PascalDragon on January 12, 2022, 09:28:50 am
Quote
Any why use larger values? There is simply no need. Using smaller types results in less stack space used which is essentially important on low-end systems. Don't forget that FPC also supports systems like i8086, Z80 and AVR which are grateful for every Byte that is available for other purposes. And we don't want to maintain even more implementations than we already have (in fact the hope is to reduce the number of different Val implementations even more to reduce the maintenance burden).
Есть причины использовать как минимум способы для подбора величины под компилируемую систему (например "define").
google translate:
There are reasons to use at least methods for choosing the value for the compiled system (for example, "define").

And there are also reasons not to use defines.

P.S. У меня складывается однозначное мнение, что вы против развития паскаля. В одном топике вы мне отвечаете одно, в другом другое... Я очень надеюсь что я ошибаюсь!!!
google translate:
P.S. I have an unambiguous opinion that you are against the development of Pascal. In one topic you answer me one thing, in another another ... I really hope that I'm wrong !!!

That may be your opinion, but it doesn't change the fact that I'm one of the FPC developers. And as such it's important for me (like any FPC dev) to weigh things like performance, cross platform compatibilty, backwards compatibility and maintainability against each other.

So in essence: you can improve StrToInt for yourself and others all you want, but for what is distributed with FPC SysUtils.StrToInt will continue to use System.Val and thus any improvement needs to happen there. And people like Bart and Isopod are doing just that currently so feel free to help them.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 12, 2022, 10:21:33 am
Alextp, Барт, thank you!
Но меня не совсем устраивает подобный подход.
Google translate:
But I am not entirely satisfied with this approach.

And there are also reasons not to use defines.
Я вас поздравляю! Вы сумели переврать мои слова! Есть способы использовать код по разные CPU, не используя defines.
А ещё, интересно то, что в коде, предоставленном Bart и Isopod как раз таки используют defines.
Вы меня хотите обмануть в чём-то?
google translate:
I congratulate you! You managed to twist my words! There are ways to use code on different CPUs without using defines.
Also, interestingly, the code provided by Bart and Isopod use defines.
Do you want to deceive me about something?
Title: Re: StrToInt in pure pascal.
Post by: Thaddy on January 12, 2022, 10:56:02 am
I like your code. And find it refreshing that you avoid conditionals and is portable Pascal.
It is also not slow.
Title: Re: StrToInt in pure pascal.
Post by: kapibara on January 12, 2022, 08:00:09 pm
@Seenkao geStrToInt returns a boolean, and not an integer, why is that?

Code: Pascal  [Select][+][-]
  1. function geStrToInt(Str: String; Size: LongWord = isInteger): Boolean;

For fun I made a small lazarus demo comparing speeds with that anyway. Not sure I used geStrToInt in the right way.  ::)

Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 12, 2022, 08:58:19 pm
@Seenkao geStrToInt returns a boolean, and not an integer, why is that?
Это производится проверка, если результат True, то можно смотреть значение, если False то значение всегда будет 0.
Само конечное значение находится в resInt64 или resQWord, опять же в зависимости от вызываемого значения-флага Size. Всё постарался расписать в самом архиве.
Всё сделано в режиме теста. Надо ещё доделывать функцию (выше основное  писали). Позже можно будет в функцию включить переменную которая будет выводить значение. Не думаю, что это займёт намного больше времени исполнения, потому что зависит в основном от самой реализации.

google translate:
This is done by checking if the result is True, then you can watch the value, if False then the value will always be 0.
The final value itself is in resInt64 or resQWord, again depending on the called Size flag value. I tried to paint everything in the archive itself.
Everything is done in test mode. We still need to finish the function (the main ones were written above). Later it will be possible to include a variable in the function that will display the value. I don't think it will take much more execution time, because it depends mostly on the implementation itself.
Title: Re: StrToInt in pure pascal.
Post by: winni on January 12, 2022, 10:31:18 pm
Hi!

I can't get your aim.
The answer is val.
It exists in every Pascal flavour I know. It exists already in the first design of Wirths early Pascal.

Don't invent the wheel again. Even if it is outdated because it was invented such a long time ago.

Winni
Title: Re: StrToInt in pure pascal.
Post by: kapibara on January 13, 2022, 01:33:58 am
@Seenkao I tried your function some more. With CONST added, geStrToInt seems more than 3 times faster than standard conversion. It would be interesting to see if that holds true also when the converted value is passed back.

However, getting the converted string back by reading resInt64 or resQWord always result in zero value?

Code: Pascal  [Select][+][-]
  1.   if geStrToInt('777',isInteger) then
  2.   begin
  3.     ShowMessage(resInt64.ToString);
  4.     ShowMessage(resQWord.ToString);
  5.   end;
  6.  
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 13, 2022, 06:13:21 am
However, getting the converted string back by reading resInt64 or resQWord always result in zero value?
Code: Pascal  [Select][+][-]
  1. procedure TForm1.FormCreate(Sender: TObject);
  2. begin
  3.   SetNumberParametr;    // this procedure must be run before using geStrToInt
  4. end;
Уж извиняюсь за неудобства. Но данные в структуре изначально не прописаны. Из-за этого функция всегда возвращает нуль.
Саму функцию я исправлю для удобства, а это будет вынужденной необходимостью.
Eng:
I do apologize for the inconvenience. But the data in the structure is not initially registered. Because of this, the function always returns zero. :-[
I will fix the function itself for convenience, and this will be a forced necessity.

I can't get your aim.
I don't force anyone. You may not use.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 17, 2022, 05:06:27 am
Rus:
Доработал модуль и добавил новые функции.

Модуль предоставляет три функции:
Code: Pascal  [Select][+][-]
  1. function geStrToInt(const Str: String; out Value: maxIntVal; Size: LongWord = isInteger): Boolean; // для десятичных чисел со знаком.
  2. function geStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isLongWord): Boolean; // для десятичных чисел без знака.
  3. function geHOBStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isQWord): Boolean; // для работы с шестнадцатеричными, восьмеричными и двоичными значениями.

 
Инициализация данных происходит при включении модуля в проект. Поэтому больше ни чего инициализировать не надо.

Модуль редактирован для разных архитектур. Проверялось только на 64-х битной системе, на 32-х битной не должно вызвать проблем. Для 16-ти и 8-ми битных надо проверять.
В модуле можно поднять уровень текущей архитектуры (UP_CPU в начале модуля). Но вы должны знать, что компилятор это позволяет и система под которую вы это делает (в основном от компилятора зависит). Для 64-х битной системы поднять уровень нельзя на данный момент. При сильном желании (если так хотите) можно, объявите свои данные и работайте с ними. Процедуры вообще не должны зависеть от разрядности системы, поэтому можно поднимать хоть до бесконечности.

Добавлен файл конфигурации.

Все функции работают быстрее стандартных (в 2-3 раза), которые используют функцию Val.

Модуль идёт под свободной лицензией Zlib.

Внимание!!! при использовании данного модуля, не включайте в отладчике флаг переполнения! Это может вызвать у вас ошибку переполнения при исполнении вашей программы.
Модуль использует способ переполнения для более быстрой обработки чисел.


При работе с шестнадцатеричными, восьмеричными и двоичными данными, вы будете работать только с без знаковыми числами UInt.
Я не считаю, что данные числа должны быть знаковыми (по моему и неудобно). Потому, если вам это необходимо, то вы сами можете доделать те функции, которые вам необходимы.

Шестнадцатеричные можно объявлять: '$', '0x' или '0X'.
Восьмеричные можно объявлять: '&' или '0' (не видел больше ни каких объявлений, если не прав, поправьте меня).
Двоичные можно объявлять: '%', '0b' или '0B'.

Тестируйте, сообщайте об ошибках. Буду править если что сделал не так. :-[

_____________________
Eng:
Modified the module and added new features.

The module provides three functions:
Code: Pascal  [Select][+][-]
  1. function geStrToInt(const Str: String; out Value: maxIntVal; Size: LongWord = isInteger): Boolean; // for signed decimal numbers.
  2. function geStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isLongWord): Boolean; // for unsigned decimal numbers.
  3. function geHOBStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isQWord): Boolean; // for working with hexadecimal, octal and binary values.
 
Data initialization occurs when the module is included in the project. Therefore, there is no need to initialize anything else.

The module has been edited for different architectures. It was tested only on a 64-bit system, it should not cause problems on a 32-bit system. For 16-bit and 8-bit it is necessary to check.
In the module, you can raise the level of the current architecture (UP_CPU at the beginning of the module). But you should know that the compiler allows it and the system under which you do it (mainly depends on the compiler). For a 64-bit system, it is impossible to raise the level at the moment. If you really want to (if you want to), you can, declare your data and work with them. Procedures in general should not depend on the bit depth of the system, so you can raise it at least indefinitely.

Added configuration file.

All functions work faster than standard ones (by 2-3 times), which use the Val function.

The module comes under the free Zlib license.

Attention!!! When using this module, do not enable the overflow flag in the debugger! This can give you an overflow error when you run your program.
The module uses an overflow method for faster processing of numbers.


When working with hexadecimal, octal, and binary data, you will only be working with unsigned UInts.
I do not believe that these numbers should be signed numbers (in my opinion, and inconveniently). Therefore, if you need it, then you yourself can complete the functions that you need.

Hexadecimal can be declared: '$', '0x' or '0X'.
Octal can be declared: '&' or '0' (didn't see any other declarations, if wrong, correct me).
Binary can be declared: '%', '0b' or '0B'.

Test, report bugs. I will correct if I did something wrong.  :-[
Title: Re: StrToInt in pure pascal.
Post by: kapibara on January 17, 2022, 06:37:40 am
Please send link or attach the updated files. Or did I miss something?
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 17, 2022, 06:57:00 am
Всё по той же ссылке. Я заменил файл. Когда будет всё готово, выложу на GitHub.

Eng:
All from the same link. I have replaced the file. When everything is ready, I will post it on GitHub.

переполнение можно обойти {$Q-} и {$R-} ???
Eng: overflow can be bypassed {$Q-} and {$R-} ???
Title: Re: StrToInt in pure pascal.
Post by: kapibara on January 17, 2022, 07:20:55 am
Thanks, I'll check it later today.

(The attached archive in your first message in this thread still has the old version)
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 17, 2022, 10:41:59 am
Thanks, I'll check it later today.

(The attached archive in your first message in this thread still has the old version)
Благодарю! Я не обратил внимания изначально. Это моя вина.
Исправил.

Eng:
Thanks to! I didn't pay attention initially. It's my fault.
Corrected.
Title: Re: StrToInt in pure pascal.
Post by: engkin on January 17, 2022, 02:49:08 pm
Eng: overflow can be bypassed {$Q-} and {$R-} ???

Yes. Just enclose them with push and pop:
Code: Pascal  [Select][+][-]
  1. {$push}{$R-}
  2. The offending command goes here
  3. {$pop}
  4.  
Title: Re: StrToInt in pure pascal.
Post by: duzenko on January 17, 2022, 03:46:17 pm
I'd post this on stackoverflow
If I'd really needed a faster version of StrToInt, I'd look for it there
Title: Re: StrToInt in pure pascal.
Post by: Kays on January 17, 2022, 05:00:02 pm
[…] Val() for unsigend integers is still broken though (it always expects the return value to be 32 or 64-bit, so it generates range check errors if you do Val('999',ByteVariable,Code), instead of just setting Code to 3 in this case).
Maybe that’s by design? Because there’s always readStr (https://www.freepascal.org/docs-html/rtl/system/readstr.html) if you want it to fail:
Code: Pascal  [Select][+][-]
  1. program unsignedConversion(input, output, stdErr);
  2. {$rangeChecks on}
  3. var
  4.         b: Byte;
  5. begin
  6.         readStr('999', b); { causes RTE 201 “range check orror” }
  7. end.
Title: Re: StrToInt in pure pascal.
Post by: Bart on January 17, 2022, 06:27:50 pm
[…] Val() for unsigend integers is still broken though (it always expects the return value to be 32 or 64-bit, so it generates range check errors if you do Val('999',ByteVariable,Code), instead of just setting Code to 3 in this case).
Maybe that’s by design?

I hardly think so.
Nor do the fpc devels.
Hence I fixed it.
(It's in a separate branch, but will be merged to trunk soo I think.)

Bart
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 18, 2022, 02:01:40 pm
I'd post this on stackoverflow
If I'd really needed a faster version of StrToInt, I'd look for it there
Вы должны понимать, что кто-то не пользуется stackoverflow (например я). Но вы можете сами предоставить решение там, указав ссылку на решение. Так же, код не проверялся на Turbo Pascal, Delphi, Pascal ABC и в таких ситуация могут предъявить претензии по компиляции кода.
Но, могут так же подсакать определённые решения для подобных проблем.  :)

google translate:
You must understand that someone does not use stackoverflow (like me). But you can provide the solution there yourself by providing a link to the solution. Also, the code has not been tested on Turbo Pascal, Delphi, Pascal ABC, and in such situations, claims can be made for compiling the code.
But, certain solutions for similar problems can also come up. :)

engkin, благодарю! Я посмотрю, чтоб код не выдавал ошибку при включенных флагах и переделаю его.
google translate:
engkin, thank you! I will see that the code does not throw an error when the flags are on and redo it.

Code: Pascal  [Select][+][-]
  1. {$push}{$R-}
  2. The offending command goes here
  3. {$pop}
And so?
Code: Pascal  [Select][+][-]
  1. {$R-}
  2. The offending command goes here
  3. {$R+}
Title: Re: StrToInt in pure pascal.
Post by: engkin on January 18, 2022, 02:39:41 pm
And so?
Code: Pascal  [Select][+][-]
  1. {$R-}
  2. The offending command goes here
  3. {$R+}

Here your code will turn range checks on for any code after your code even if range checks were off in the project settings and before your code..
Title: Re: StrToInt in pure pascal.
Post by: Zoran on January 18, 2022, 03:08:09 pm
Here your code will turn range checks on for any code after your code even if range checks were off in the project settings and before your code..

Yes, make a habit of using {$pop} and {$push}, it's a really good practice.

Also, about {$R} and {$Q} directives, I always use both -- either turn both on or off. Read this: https://wiki.freepascal.org/local_compiler_directives#.24R_versus_.24Q (https://wiki.freepascal.org/local_compiler_directives#.24R_versus_.24Q)

Code: Pascal  [Select][+][-]
  1. {$push}
  2. {$R-}{$Q-}
  3. The offending command goes here
  4. {$pop}
  5.  
Title: Re: StrToInt in pure pascal.
Post by: Thaddy on January 18, 2022, 03:17:06 pm
Yes, make a habit of using {$pop} and {$push}, it's a really good practice.
Totally agree. Note that for Delphi compatible code this takes more effort.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 18, 2022, 08:04:17 pm
Благодарю за информацию!  :) Про "push" и "pop" я должен был догадаться... ведь в самом деле состояние могло быть изначально не включено.

Вопрос другой, если я включу это в блок процедуры или вообще на весь модуль - это сработает? Не будет ли состояние неизменным (если я отключил его) при вызове "Exit"? Или вернётся в прежнее состояние?

Точнее мне надо отделить команды определённые или я могу отделить полностью модуль/процедуру/функцию? Не повлияет это на код пользователя?

google translate:
Thank you for the information!  :) About "push" and "pop" I should have guessed... after all, in fact, the state could not be included initially.

The question is different, if I include it in the procedure block or in general for the whole module - will it work? Won't the state be immutable (if I disabled it) when "Exit" is called? Or will it return to its original state?

More precisely, do I need to separate certain commands or can I separate the module / procedure / function completely? Will this affect the user code?
Title: Re: StrToInt in pure pascal.
Post by: engkin on January 18, 2022, 08:46:51 pm
Any code gets compiled AFTER {$R+} till it meets:
{$R-} or
end of this unit or
{$pop} with the proper push & R
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 18, 2022, 10:17:02 pm
Всем спасибо!

Проблема с диапазонами решена. Потому можно использовать без опасения на выход с ошибкой. Файл выложен под той же ссылкой (в первоначальном посте так же выложен).

Как обычно, выкладывайте тесты, которые привели к неправильному поведению функций. ))) Буду исправлять, если таковые имеются.

google translate:
Thank you all!

The problem with ranges is solved. Therefore, you can use it without fear of an exit with an error. The file is posted under the same link (in the original post it is also posted).

As usual, post the tests that led to the incorrect behavior of the functions. ))) I will correct, if any.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 19, 2022, 01:59:10 pm
Хотел узнать, полезно будет или нет реализовать дополнительные функции?
Данные функции будут ориентированы на определённый тип данных. А так же для функций с числами без знака можно объединить с функциями работающими с шестнадцатеричными, восьмеричными и двоичными числами.

google translate:
 I wanted to know if it would be useful or not to implement additional functions?
These functions will target a specific data type. And also for functions with unsigned numbers, it can be combined with functions working with hexadecimal, octal and binary numbers.

Code: Pascal  [Select][+][-]
  1. function StrToIShort(const Str: String): ShortInt;
  2. function StrToISmall(const Str: String): SmallInt;
  3. function StrToInt(const Str: String): Integer;
  4. function StrToInt64(const Str: String): Int64;
  5.  
  6. function StrToByte(const Str: String): Byte;
  7. function StrToWord(const Str: String): Word;
  8. function StrToLWord(const Str: String): LongWord;
  9. function StrToQWord(const Str: String): QWord;
Title: Re: StrToInt in pure pascal.
Post by: AlexTP on January 19, 2022, 02:10:24 pm
IMO it's not needed. New function names are not needed. When your unit is used, user already knows he wants the speed, and he uses your func name.
Title: Re: StrToInt in pure pascal.
Post by: Thaddy on January 19, 2022, 02:16:55 pm
except for unit order that is. Do not overlook that.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 19, 2022, 02:48:33 pm
Думаю вы правы.
Благодарю!

Eng:
I think you are right.
Thanks!
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 19, 2022, 06:25:03 pm
Но я не смог не предоставить версии для общего использования. :-[ По моему мнению, функции, предоставленные мной, не достаточно удобны для обычного пользователя. Потому я ввёл дополнительные функции, с которыми пользователю проще работать. В количестве 16. ::)
google translate:
But I couldn't help but provide versions for general use. :-[ In my opinion, the functions provided by me are not convenient enough for the average user. Therefore, I introduced additional functions that are easier for the user to work with. In the amount of 16. ::)

Code: Pascal  [Select][+][-]
  1. (* Rus: Ниже реализованы стандартные функции для перевода строк в число. Их
  2.  *      использование будет проще для большинства. Функции отмечены префиксом.
  3.  *      s_ - функции возвращают результат (если операция была неудачной, то
  4.  *      в результате вернётся ноль, но вы не узнаете, что операция была неудачной).
  5.  *      sc_ - результат функций удачная или не удачная была операция. Сам
  6.  *      конечный числовой результат считывайте в Value.
  7.  * Eng: The standard functions for converting strings to numbers are implemented
  8.  *      below. Their use will be easier for most. Functions are marked with a prefix.
  9.  *      s_ - functions return a result (if the operation was unsuccessful, the result
  10.  *      will be zero, but you will not know that the operation was unsuccessful).
  11.  *      sc_ - the result of the functions - the operation was successful or
  12.  *      unsuccessful. Read the final numerical result in Value.
  13.  *)
  14.  
  15. // Rus: Числа со знаком. Здесь нельзя использовать шестнадцатеричные, восьмеричные
  16. //      и двоичные числа.
  17. // Eng: Signed numbers. Hexadecimal, octal and binary numbers cannot be used here.
  18. function sc_StrToShortInt(const Str: String; out Value: ShortInt): Boolean;    // byte
  19. function s_StrToShortInt(const Str: String): ShortInt;                         // byte
  20. function sc_StrToSmallInt(const Str: String; out Value: SmallInt): Boolean;    // word
  21. function s_StrToSmallInt(const Str: String): SmallInt;                         // word
  22. function sc_StrToInt(const Str: String; out Value: Integer): Boolean;
  23. function s_StrToInt(const Str: String): Integer;
  24. function sc_StrToInt64(const Str: String; out Value: Int64): Boolean;
  25. function s_StrToInt64(const Str: String): Int64;
  26.  
  27. // Rus: Числа без знака. Эти функции могут использоваться и для шестнадцатеричныи
  28. //      и восьмеричных и двоичных чисел.
  29. // Eng: Numbers without a sign. These functions can be used for hexadecimal, octal
  30. //      and binary numbers as well.
  31. function sc_StrToByte(const Str: String; out Value: Byte): Boolean;
  32. function s_StrToByte(const Str: String): Byte;
  33. function sc_StrToWord(const Str: String; out Value: Word): Boolean;
  34. function s_StrToWord(const Str: String): Word;
  35. function sc_StrToLongWord(const Str: String; out Value: LongWord): Boolean;
  36. function s_StrToLongWord(const Str: String): LongWord;
  37. function sc_StrToQWord(const Str: String; out Value: QWord): Boolean;
  38. function s_StrToQWord(const Str: String): QWord;  

Все функции критичны к архитектуре и на 16-ти битной архитектуре не будет функций sc_StrToInt, s_StrToInt64, sc_StrToLongWord и подобных. Они исключаться (если вы не использовали define UP_CPU).
google translate:
All functions are critical to the architecture and there will be no sc_StrToInt, s_StrToInt64, sc_StrToLongWord and similar functions on a 16-bit architecture. They are excluded (unless you used define UP_CPU).
Title: Re: StrToInt in pure pascal.
Post by: AlexTP on January 19, 2022, 06:28:52 pm
Can you put this unit to GitHub? Please. I tried to download file from the 1st post (Yandex.disk) and got Yandex warning (it suggests to login).
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 19, 2022, 06:34:38 pm
Yes OK! I'll take care of it now.

until then I'll post it here.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 19, 2022, 11:56:49 pm
GitHub: fast_StrToInt (https://github.com/Seenkao/fast_StrToInt.git)
Все старые версии, с маленькими глюками, последний код так же надо проверять. Надеюсь что устранил все ошибки, но это вряд ли. )))

google translate:
All old versions, with small glitches, the latest code also needs to be checked. I hope that eliminated all the errors, but it is unlikely. )))

Всем большое спасибо! И за не лестные отзывы тоже! Почти все они мне пригодились выявлять ошибки в коде.
google translate:
Thank you all! And for the bad reviews too! Almost all of them were useful to me to identify errors in the code. ;)
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 20, 2022, 07:58:19 am
Мелочи, мелочи, мелочи...
Решил проблему с восьмеричной системой счисления (надеюсь всё, хотя кто его знает).
Добавил define ADD_FAST - он немного ускорит работу пользовательских функций, и немного увеличит код. На основные функции ни как не влияет.
Произвёл небольшую оптимизацию кода.
... пора бы уже заканчивать...  :)

google translate:
Little things, little things, little things...
I solved the problem with the octal number system (I hope everything, although who knows).
Added define ADD_FAST - it will slightly speed up the work of custom functions, and slightly increase the code. It does not affect the main functions in any way.
Made some code optimizations.
... it's time to finish already ... :)
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 23, 2022, 12:05:19 am
Теперь три основные функции удаляют ведущие нули.
Пользовательские функции тоже, но функции:
sc_StrToByte, s_StrToByte, sc_StrToWord, s_StrToWord, sc_StrToLongWord, s_StrToLongWord, sc_StrToQWord и s_StrToQWord - не должны содержать ведущие нули для десятичной системы счисления.
Google translate:
Now the three main functions remove leading zeros.
Custom functions too, but functions:
sc_StrToByte, s_StrToByte, sc_StrToWord, s_StrToWord, sc_StrToLongWord, s_StrToLongWord, sc_StrToQWord and s_StrToQWord - must not contain leading zeros for the decimal number system.
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on January 31, 2022, 09:21:34 pm
в файле конфигурации добавил возможность выбора "вида строки", на выбор:
Code: [Select]
{$DEFINE USE_STRING} // String
{$DEFINE USE_ANSISTRING} // AnsiString
{$DEFINE USE_UNICODESTRING} // UnicodeString
{$DEFINE USE_UTF8STRING} //UTF8String
Если в своём коде вы используете какой-то из видов строк, то лучше переключать дефайны. Иначе можно потерять в скорости из-за перевода строки из одного вида в другой.
Дефайны действуют в порядке приоритета сверху вниз. Нижние отключаться, если какой-то из верхних включен.

Так же мелкое исправление в коде, функция geStrToUInt (и все зависимые от неё) могли выдать ошибку при подсчёте.

Да, да, я знаю, что нужны функции для разных видов строк. Но лично я считаю, что неправильно прыгать с одного вида строк на другой.

google translate:
added the ability to select the "string type" in the configuration file, to choose from:
Code: [Select]
{$DEFINE USE_STRING} // String
{$DEFINE USE_ANSISTRING} // AnsiString
{$DEFINE USE_UNICODESTRING} // UnicodeString
{$DEFINE USE_UTF8STRING} //UTF8String
If in your code you use one of the types of strings, then it is better to switch defines. Otherwise, you can lose speed due to the translation of a string from one type to another.
Defines operate in order of priority from top to bottom. The lower ones will turn off if any of the upper ones is on.

Also a minor fix in the code, the function geStrToUInt (and all dependent on it) could give an error when calculating.

Yes, yes, I know that functions are needed for different kinds of strings. But personally, I think it's wrong to jump from one string type to another. ::)

-->fast_StrToInt download. (https://github.com/Seenkao/fast_StrToInt.git)<-- ;)
Title: Re: StrToInt in pure pascal.
Post by: Seenkao on February 03, 2022, 04:50:32 pm
Основа была полностью переработана и теперь всё основывается на шести функциях (можно отключать по желанию три первых или три последних):
Eng: The base has been completely redesigned and now everything is based on six functions (you can turn off the first three or the last three at will):
Code: Pascal  [Select][+][-]
  1. function geCharToInt(const aStr: array of Char; out Value: maxIntVal; Size: maxIntVal = maxSize): Boolean;
  2. function geCharToUInt(const aStr: array of Char; out Value: maxUIntVal; Size: maxIntVal = maxSize): Boolean;
  3. function geHOBCharToUInt(const aStr: array of Char; out Value: maxUIntVal; Size: maxIntVal = maxSize): Boolean;
  4.  
  5. // for unicode
  6. function geWCharToInt(const aStr: array of WideChar; out Value: maxIntVal; Size: maxIntVal = maxSize): Boolean;
  7. function geWCharToUInt(const aStr: array of WideChar; out Value: maxUIntVal; Size: maxIntVal = maxSize): Boolean;
  8. function geWHOBCharToUInt(const aStr: array of WideChar; out Value: maxUIntVal; Size: maxIntVal = maxSize): Boolean;

Остальные функции дублированы для юникода. Описание на GitHub (https://github.com/Seenkao/fast_StrToInt).
Протестировал насколько возможно, но лишними тесты ни когда не будут.  :)
Обратите внимание!!! Если вы работаете с UTF8String и вы не включите дефайн USE_UTF8STRING, вы можете не получить ни какого ускорения!!!
Максимальное ускорение работы кода, только в том случае если используемые типы совпадают.
google translate:
The remaining functions are duplicated for Unicode. Description at GitHub (https://github.com/Seenkao/fast_StrToInt).
I tested as much as possible, but tests will never be superfluous. :)
Note!!! If you are working with UTF8String and you don't include USE_UTF8STRING define, you may not get any speedup!!!
The maximum speedup of the code, only if the used types match.
Title: Re: StrToInt in pure pascal.
Post by: ASBzone on February 08, 2022, 04:46:44 pm
except for unit order that is. Do not overlook that.


Please elaborate, Thaddy...

Are you talking about "uses" order? or something else?
Title: Re: StrToInt in pure pascal.
Post by: Thaddy on February 08, 2022, 08:06:36 pm
except for unit order that is. Do not overlook that.


Please elaborate, Thaddy...

Are you talking about "uses" order? or something else?
Uses order...
Title: Re: StrToInt in pure pascal.
Post by: ASBzone on February 08, 2022, 11:21:20 pm
Uses order...


Thanks
TinyPortal © 2005-2018