Rus:Всем привет!
Я доделал функцию StrToInt, как оказалось, она имела определённые ошибки, которые выявились в процессе общения в соседних топиках. Можно поблагодарить людей, которые помогли мне (сами того не зная).
Было бы неплохо, если бы вы проверили её на работоспособность.
-->fast_StrToInt скачать<-- Зачем я это сделал? Функция быстрее работает на процессорах x86 чуть менее чем в два раза, на процессорах ARM быстрее, но я не помню насколько. А так как зачастую в программах используется перевод строковых значений в числа, то я думаю это немалый прирост в скорости.
Обратите внимание! Данная библиотека рассчитана на скорость перевода строки в число! А так же на совместимость с разными архитектурами. Но обрабатывает она только числа, знак "-" (минус) и префиксы для шестнадцатеричной, восмеричной и двоичной систем. Все остальные символы будут игнорированы и в этом случае все функции будут выдавать не верный результат (даже если вы просто поставите пробел перед числом).плюсы (+):
быстрее скорость работы, сделано на чистом паскале, подойдёт для любой платформы и архитектуры (по крайней мере должны).
Функция не вылетит с ошибкой! Результат функции булева переменная сообщающая успешен был перевод или нет, сам результат в Value.
Функция позволяет выбирать размерность обрабатываемых данных.
минусы (-): просьба собщить о минусах функций. Я их создавал. Потому мой взгляд однобокий.
примеры использования в программе. Сама функция
geStrToInt в соседнем модуле. Пример сделан для разных систем Linux/Windows (возможно и MacOS но не совсем уверен в дефайнах).
Модуль предоставляет 16 пользовательских функций, основанных на трёх основных:
(* Rus: Ниже реализованы стандартные функции для перевода строк в число. Их
* использование будет проще для большинства. Функции отмечены префиксом.
* s_ - функции возвращают результат (если операция была неудачной, то
* в результате вернётся ноль, но вы не узнаете, что операция была неудачной).
* sc_ - результат функций удачная или не удачная была операция. Сам
* конечный числовой результат считывайте в Value.
*)
// Rus: Числа со знаком. Здесь нельзя использовать шестнадцатеричные, восьмеричные
// и двоичные числа.
function sc_StrToShortInt(const Str: String; out Value: ShortInt): Boolean; // byte
function s_StrToShortInt(const Str: String): ShortInt; // byte
function sc_StrToSmallInt(const Str: String; out Value: SmallInt): Boolean; // word
function s_StrToSmallInt(const Str: String): SmallInt; // word
function sc_StrToInt(const Str: String; out Value: Integer): Boolean;
function s_StrToInt(const Str: String): Integer;
function sc_StrToInt64(const Str: String; out Value: Int64): Boolean;
function s_StrToInt64(const Str: String): Int64;
// Rus: Числа без знака. Эти функции могут использоваться и для шестнадцатеричныи
// и восьмеричных и двоичных чисел. Данные функции не должны содержать
// ведущие нули для десятеричной системы счисления.
function sc_StrToByte(const Str: String; out Value: Byte): Boolean;
function s_StrToByte(const Str: String): Byte;
function sc_StrToWord(const Str: String; out Value: Word): Boolean;
function s_StrToWord(const Str: String): Word;
function sc_StrToLongWord(const Str: String; out Value: LongWord): Boolean;
function s_StrToLongWord(const Str: String): LongWord;
function sc_StrToQWord(const Str: String; out Value: QWord): Boolean;
function s_StrToQWord(const Str: String): QWord;
Модуль предоставляет три основных функции:
function geStrToInt(const Str: String; out Value: maxIntVal; Size: LongWord = isInteger): Boolean; // для десятичных чисел со знаком.
function geStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isLongWord): Boolean; // для десятичных чисел без знака.
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:
(*
* Eng: The standard functions for converting strings to numbers are implemented
* below. Their use will be easier for most. Functions are marked with a prefix.
* s_ - functions return a result (if the operation was unsuccessful, the result
* will be zero, but you will not know that the operation was unsuccessful).
* sc_ - the result of the functions - the operation was successful or
* unsuccessful. Read the final numerical result in Value.
*)
// Eng: Signed numbers. Hexadecimal, octal and binary numbers cannot be used here.
function sc_StrToShortInt(const Str: String; out Value: ShortInt): Boolean; // byte
function s_StrToShortInt(const Str: String): ShortInt; // byte
function sc_StrToSmallInt(const Str: String; out Value: SmallInt): Boolean; // word
function s_StrToSmallInt(const Str: String): SmallInt; // word
function sc_StrToInt(const Str: String; out Value: Integer): Boolean;
function s_StrToInt(const Str: String): Integer;
function sc_StrToInt64(const Str: String; out Value: Int64): Boolean;
function s_StrToInt64(const Str: String): Int64;
// Eng: Numbers without a sign. These functions can be used for hexadecimal, octal
// and binary numbers as well. These functions must not contain leading zeros
// for the decimal number system.
function sc_StrToByte(const Str: String; out Value: Byte): Boolean;
function s_StrToByte(const Str: String): Byte;
function sc_StrToWord(const Str: String; out Value: Word): Boolean;
function s_StrToWord(const Str: String): Word;
function sc_StrToLongWord(const Str: String; out Value: LongWord): Boolean;
function s_StrToLongWord(const Str: String): LongWord;
function sc_StrToQWord(const Str: String; out Value: QWord): Boolean;
function s_StrToQWord(const Str: String): QWord;
The module provides three main functions:
function geStrToInt(const Str: String; out Value: maxIntVal; Size: LongWord = isInteger): Boolean; // for signed decimal numbers.
function geStrToUInt(const Str: String; out Value: maxUIntVal; Size: LongWord = isLongWord): Boolean; // for unsigned decimal numbers.
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.