Voting

: min(five, zero)?
(Example: nine)

The Note You're Voting On

divinity76 at gmail dot com
3 years ago
if you for some reason need a base10 / pure-number encode instead, encoding to some combination of 0123456789

<?php
// base10-encode using the dictionary 0123456789
function base10_encode(string $str): string
{
$ret = "";
for (
$i = 0, $imax = strlen($str); $i < $imax; ++ $i) {
$ret .= str_pad((string) ord($str[$i]), 3, "0", STR_PAD_LEFT);
}
return
$ret;
}
// base10-decode using the dictionary 0123456789
function base10_decode(string $str): string
{
$ret = "";
for (
$i = 0, $imax = strlen($str); $i < $imax; $i += 3) {
// notably here we are using (int) to trim away the zeroes..
$ret .= chr((int) substr($str, $i, 3));
}
return
$ret;
}
?>

it is unicode-safe and binary-safe, testing:

<?php
// simple ascii test:
$d=[];
$d["raw"]="test";
$d["b10"]=base10_encode($d["raw"]); // 116101115116
$d["decoded"]=base10_decode($d["b10"]); // test
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false
var_dump($d);
// complex unicode test:
$d=[];
$d["raw"]="ˈmaʳkʊs kuːn ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (A ⇔ B), Σὲ γνωρίζω ἀπὸ τὴν κόψη Οὐχὶ ταὐτὰ παρίσταταί გთხოვთ ሰማይ አይታረስ ንጉሥ አይከሰስ ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ ";
// lets add some chess for good measure
$d["raw"].="♔♕♖♗♘♙♚♛♜♝♞🙾🙿";
$d["b10"]=base10_encode($d["raw"]); //
$d["decoded"]=base10_decode($d["b10"]);
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false, base10 is unicode safe :D
var_dump($d);
// binary safety test:
$everything="";
for(
$i=0;$i<=0xFF;++$i){
$everything.=chr($i);
}
$d=[];
$d["raw"]=$everything;
$d["b10"]=base10_encode($d["raw"]);
$d["decoded"]=base10_decode($d["b10"]);
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false :D base10 is binary safe.
var_dump($d);

?>

<< Back to user notes page

To Top