Recent

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

Seenkao

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

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

Bart

  • Hero Member
  • *****
  • Posts: 5289
    • Bart en Mariska's Webstek
Re: StrToInt in pure pascal.
« Reply #16 on: January 11, 2022, 03:31:18 pm »
In the bugtracker thread about this, Isopod posted already faster algorithms for Val.

Bart

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #17 on: January 11, 2022, 03:50:08 pm »
Благодарю за информацию!
Где её можно посмотреть?

google translate:
Thank you for the information!
Where can you watch it? :-[
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

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


Bart

  • Hero Member
  • *****
  • Posts: 5289
    • Bart en Mariska's Webstek
Re: StrToInt in pure pascal.
« Reply #19 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 is the implementation proposal of Isopod.

See the extended discussion in this bugtracker issue.

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

PascalDragon

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

Seenkao

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

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

Thaddy

  • Hero Member
  • *****
  • Posts: 14367
  • Sensorship about opinions does not belong here.
Re: StrToInt in pure pascal.
« Reply #22 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.
Object Pascal programmers should get rid of their "component fetish" especially with the non-visuals.

kapibara

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

« Last Edit: January 12, 2022, 08:20:49 pm by kapibara »
Lazarus trunk / fpc 3.2.2 / Kubuntu 22.04 - 64 bit

Seenkao

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

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

winni

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

kapibara

  • Hero Member
  • *****
  • Posts: 610
Re: StrToInt in pure pascal.
« Reply #26 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.  
Lazarus trunk / fpc 3.2.2 / Kubuntu 22.04 - 64 bit

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: StrToInt in pure pascal.
« Reply #27 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.
« Last Edit: January 13, 2022, 06:15:32 am by Seenkao »
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 #28 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.  :-[
« Last Edit: January 17, 2022, 05:45:00 am by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

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

kapibara

  • Hero Member
  • *****
  • Posts: 610
Re: StrToInt in pure pascal.
« Reply #29 on: January 17, 2022, 06:37:40 am »
Please send link or attach the updated files. Or did I miss something?
Lazarus trunk / fpc 3.2.2 / Kubuntu 22.04 - 64 bit

 

TinyPortal © 2005-2018