Created
March 20, 2024 17:20
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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