note 126301 added to function.base64-encode
| From: | divinity76 at gmail dot com | Date: | Mon, 02 Aug 2021 07:58:26 +0000 |
| Subject: | note 126301 added to function.base64-encode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216715@lists.php.net to get a copy of this message | ||
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);
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 84.48.255.36)
----
Manual Page -- https://php.net/manual/en/function.base64-encode.php
Edit -- https://main.php.net/note/edit/126301
Del: integrated -- https://main.php.net/note/delete/126301/integrated
Del: useless -- https://main.php.net/note/delete/126301/useless
Del: bad code -- https://main.php.net/note/delete/126301/bad+code
Del: spam -- https://main.php.net/note/delete/126301/spam
Del: non-english -- https://main.php.net/note/delete/126301/non-english
Del: in docs -- https://main.php.net/note/delete/126301/in+docs
Del: other reasons-- https://main.php.net/note/delete/126301
Reject -- https://main.php.net/note/reject/126301
Search -- https://main.php.net/manage/user-notes.php