AFAIK the usual StrToInt is based on Val().Функция Val достаточно давно создана и по моему мнению достаточно большая часть из неё устарела, потому что от Val требовали достаточно многого. Функция достаточно универсальна, но делалась в стародавние времена и я не уверен что кто-то за неё вообще брался за это время (могу ошибаться).
So better rewrite Val(), not StrToInt / StrToDWord / StrToQWord / StrToByte.
It will be not simple for you.Почему вы за меня что-то решаете? :) На самом деле разные форматы добавить намного проще, чем создать функцию основу StrToInt. При чём, вы забываете, что многое сделано до меня, я лишь это всё собрал и оптимизировал.
Because Val also supports hex/octal/bin formats.да, да, а так же перевод чисел с плавающей запятой.
use:Благодарю! Я был в сомнениях какие дефайны правильно использовать. А где можно посмотреть более подробную информацию по defines?
{$ifdef CPU64}
And on the translation of hexadecimal/octal/binary numbers, a natural question arises, and should the "-" sign participate there at all?
and should the "-" sign participate there at all?
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
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).
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 не устарел?
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 hurrybytes? Seriously? On 32-bit, 64-bit systems?
base, u: byte; ... base, len, baseindex: byte;
The question is why? So that the compiler additionally spent the cost of translating numbers?
If it would be "out of date" it wouldn't be 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.ещё раз повторюсь, большая. Не надо рассказывать что поломка и улучшение - это одно и то же. Поломка - это когда надо восстановить работоспособность. Улучшение - это изменение функции для улучшения её работоспособности и ускорения скорости её работы, а так же по возможности исключения возникновения ошибок при её работе.
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").
This commit
https://gitlab.com/freepascal.org/fpc/source/-/commit/beecbf1581a986f544fde77aa428e05c21a35f6f
QuoteAny 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 !!!
And there are also reasons not to use defines.Я вас поздравляю! Вы сумели переврать мои слова! Есть способы использовать код по разные CPU, не используя defines.
@Seenkao geStrToInt returns a boolean, and not an integer, why is that?Это производится проверка, если результат True, то можно смотреть значение, если False то значение всегда будет 0.
However, getting the converted string back by reading resInt64 or resQWord always result in zero value?
I can't get your aim.I don't force anyone. You may not use.
Thanks, I'll check it later today.Благодарю! Я не обратил внимания изначально. Это моя вина.
(The attached archive in your first message in this thread still has the old version)
Eng: overflow can be bypassed {$Q-} and {$R-} ???
[…] 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:
[…] 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'd post this on stackoverflowВы должны понимать, что кто-то не пользуется stackoverflow (например я). Но вы можете сами предоставить решение там, указав ссылку на решение. Так же, код не проверялся на Turbo Pascal, Delphi, Pascal ABC и в таких ситуация могут предъявить претензии по компиляции кода.
If I'd really needed a faster version of StrToInt, I'd look for it there
And so?
{$push}{$R-} The offending command goes here {$pop}
And so?
{$R-} The offending command goes here {$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..
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.
{$DEFINE USE_STRING} // String
{$DEFINE USE_ANSISTRING} // AnsiString
{$DEFINE USE_UNICODESTRING} // UnicodeString
{$DEFINE USE_UTF8STRING} //UTF8String
Если в своём коде вы используете какой-то из видов строк, то лучше переключать дефайны. Иначе можно потерять в скорости из-за перевода строки из одного вида в другой.{$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.except for unit order that is. Do not overlook that.
Uses order...except for unit order that is. Do not overlook that.
Please elaborate, Thaddy...
Are you talking about "uses" order? or something else?
Uses order...