将二进制数转换为Base 64 [英] Convert a binary number to Base 64
问题描述
我知道这是一个非常愚蠢的问题,但是我不知道该怎么办.
I know this is a pretty silly question, but I don't know what to do.
我有一个任意的二进制数,
I have an arbitrary binary number, say,
1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111
我想使用PHP将其转换为Base 64-我尝试的每种方式都给我不同的结果.甚至不同的在线转换器对它的转换也不同:
I want to convert it to Base 64 using PHP - and every way I try gives me a different result. Even different online converters convert it differently:
http://home2.paulschou.net/tools/xlate/
http://convertxy.com/index.php/numberbases/
PHP的base_convert最多只能使用base36,而base64_encode需要一个字符串.
PHP's base_convert only works up to base36, and base64_encode expects a string.
我该怎么办?
更新:我实现了 @binaryLV 建议的解决方案功能,并且运行良好.
UPDATE: I implemented the solution functions suggested by @binaryLV, and it did work well.
但是,我将结果与PHP内置的 base_convert 进行了比较.事实证明,将base_convert转换为base36会返回比自定义base64函数更短的值! (是的,我确实在所有二进制数字前加了"1",以确保不会丢失前导零).
However, I compared the results to PHP's built-in base_convert. It turned out that base_convert to base36 returns shorter values that the custom base64 function! (And yes, I did prepend a '1' to all the binary numbers to ensure leading zeros aren't lost).
我也注意到, base_convert 与大量数字无关.因此,我需要一个功能类似于base_convert的函数,但要准确地且最好是直到base 64.
I have noticed, too, that base_convert is quite innacurate with large numbers. So I need is a function which works like base_convert, but accurately and, preferably, up to base 64.
推荐答案
示例中字符串的长度为160.这让我认为它包含有关160/8个字符的信息.所以,
Length of a string in example is 160. It makes me think that it holds info about 160/8 characters. So,
- 将字符串分割成多个部分,每个部分包含8个二进制数字并描述单个字符
- 将每个部分转换为十进制整数
- 使用第二步的ASCII码制作的字符构建字符串
这将与大小为n*8
的字符串一起使用.对于其他字符串(例如12个二进制数字),则会产生意外的结果.
This will work with strings with size n*8
. For other strings (e.g., 12 binary digits) it will give unexpected results.
代码:
function bin2base64($bin) {
$arr = str_split($bin, 8);
$str = '';
foreach ( $arr as $binNumber ) {
$str .= chr(bindec($binNumber));
}
return base64_encode($str);
}
$bin = '1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111';
echo bin2base64($bin);
结果:
kDICQIMBEFjDBxwMBJiAASBYwgc=
这里还具有将其解码回二进制数字字符串的功能:
Here's also function for decoding it back to string of binary digits:
function base64bin($str) {
$result = '';
$str = base64_decode($str);
$len = strlen($str);
for ( $n = 0; $n < $len; $n++ ) {
$result .= str_pad(decbin(ord($str[$n])), 8, '0', STR_PAD_LEFT);
}
return $result;
}
var_dump(base64bin(bin2base64($bin)) === $bin);
结果:
boolean true
这篇关于将二进制数转换为Base 64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!