Recent

Author Topic: StrToInt in pure pascal.  (Read 20787 times)

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
StrToInt in pure pascal.
« on: January 10, 2022, 02:33:39 pm »
Rus:
Всем привет!

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

Было бы неплохо, если бы вы проверили её на работоспособность.
-->fast_StrToInt скачать<-- ;)

Зачем я это сделал? Функция быстрее работает на процессорах 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.<-- ;)

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.  :-[
« Last Edit: January 31, 2022, 09:29:09 pm by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

AlexTP

  • Hero Member
  • *****
  • Posts: 2399
    • UVviewsoft
Re: StrToInt in pure pascal.
« Reply #1 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.
« Last Edit: January 10, 2022, 04:38:34 pm by Alextp »

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #2 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? :)
« Last Edit: January 10, 2022, 05:40:03 pm by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: StrToInt in pure pascal.
« Reply #3 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}

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #4 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.
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

AlexTP

  • Hero Member
  • *****
  • Posts: 2399
    • UVviewsoft
Re: StrToInt in pure pascal.
« Reply #5 on: January 10, 2022, 05:59:48 pm »

engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: StrToInt in pure pascal.
« Reply #6 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

AlexTP

  • Hero Member
  • *****
  • Posts: 2399
    • UVviewsoft
Re: StrToInt in pure pascal.
« Reply #7 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 '-'.

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #8 on: January 10, 2022, 07:20:38 pm »
Thanks for the information! ;)
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #9 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.
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Bart

  • Hero Member
  • *****
  • Posts: 5288
    • Bart en Mariska's Webstek
Re: StrToInt in pure pascal.
« Reply #10 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

PascalDragon

  • Hero Member
  • *****
  • Posts: 5462
  • Compiler Developer
Re: StrToInt in pure pascal.
« Reply #11 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 due to some problems encountered there and its performance is under review as well. So to say that it's outdated is absolutely wrong.

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #12 on: January 11, 2022, 12:29:38 pm »
The most recent changes were just a few hours ago due to some problems encountered there 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! :)
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

PascalDragon

  • Hero Member
  • *****
  • Posts: 5462
  • Compiler Developer
Re: StrToInt in pure pascal.
« Reply #13 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).

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #14 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 !!!
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

 

TinyPortal © 2005-2018