Convert a string to number and back to string?

痴心易碎 提交于 2019-11-29 00:17:20

A string-to-number encoder as one-liner (PHP 5.3 style):

$numbers = join(array_map(function ($n) { return sprintf('%03d', $n); },
                          unpack('C*', $str)));

It simply converts every byte into its decimal number equivalent, zero-padding it to a fixed length of 3 digits so it can be unambiguously converted back.

The decoder back to a string:

$str = join(array_map('chr', str_split($numbers, 3)));

Example text:

Wörks wíth all ストリングズ
087195182114107115032119195173116104032097108108032227130185227131136227131170227131179227130176227130186

You can't just ORD chars into a string of numbers and expect it to come back because some chars may be on 2 characters and others 3.

For example:

Kang-HO will give you: 10797106103457279

Now how do you know it's not: 10-79-71-0-61-0-34-57-27-9?

You need to either pad all your numbers in 3 number codes and thus get: 107097106103045072079 and then break it apart in blocks of 3 numbers and then ASC them back...

Well, if you want to convert your string into a sequence of integers you must use always a fixed block of numbers. In this case 3 since ASCII uses a 8 bit words, therefore, the maximun possible integer is 2^8-1 = 255.

You should fill the unsed space with 0:

function zero_fill($num){
    if($num <= 9) $num = "00".$num;
    elseif($num <= 99) $num = "0".$num;
    return $num;
}

You can use the function you have created in conjuction with this one, and to recover the string, take block of 3 integers and convert them back to its correspondant ASCII character.

foreach(str_split($numberSeq, 3) as $asciiIntValue) $stringBack .= chr($asciiIntValue);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!