Skip to content

Instantly share code, notes, and snippets.

@attitude
Created March 20, 2024 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attitude/304921838815d9ee6e3424c05b3d0dfd to your computer and use it in GitHub Desktop.
Save attitude/304921838815d9ee6e3424c05b3d0dfd to your computer and use it in GitHub Desktop.
Converts a string to an integer by calculating the sum of the ASCII values of its characters.
<?php declare(strict_types = 1);
/**
* Converts a string to an integer by calculating the sum of the ASCII values of its characters.
* @license MIT
*
* @param string $string The input string to convert.
* @return int The resulting integer value.
* @throws \RangeException If the input string to encode contains an invalid character.
*/
function word_ord(string $string): int {
if (strlen($string) > PHP_INT_SIZE) {
throw new \OverflowException('String is too long to be converted to an integer');
}
$integer = 0;
for ($i = 0; $i < strlen($string); $i++) {
$ord = ord($string[$i]);
if ($ord >= 33 && $ord <= 126) {
$integer += $ord * (256 ** $i);
} else {
throw new \RangeException('Invalid character out of range');
}
}
return $integer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment