Skip to content

Instantly share code, notes, and snippets.

@attitude
Created March 20, 2024 17:21
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/527d13ef85ebd45d628c86ba58a119c3 to your computer and use it in GitHub Desktop.
Save attitude/527d13ef85ebd45d628c86ba58a119c3 to your computer and use it in GitHub Desktop.
Converts an integer to a string by mapping each byte to its corresponding ASCII character.
<?php declare(strict_types = 1);
/**
* Converts an integer to a string by mapping each byte to its corresponding ASCII character.
* @license MIT
*
* @param int $int The integer to convert.
* @return string The resulting string.
* @throws \RangeException If the decoded character is out of the valid ASCII range (33-126).
*/
function chr_word(int $int): string {
$string = '';
while ($int > 0) {
$ord = $int % 256;
if ($ord >= 33 && $ord <= 126) {
$string .= chr($ord);
$int = intdiv($int, 256);
} else {
throw new \RangeException("Character out of range");
}
}
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment