我想解码十六进制编码的二进制字符串;它将通过使用 hex2bin 来工作PHP 的功能。但我在 ColdFusion 中也需要同样的东西。
PHP
$key="43480170";
echo hex2bin($key);
输出:CHp
我已经尝试过以下代码。但是这个 ColdFusion 代码没有给出我在 PHP 中得到的结果;
ColdFusion
<cfset key="43480170" />
<cfoutput>#binaryDecode(key, "hex" ).toString()#</cfoutput>
输出:每次运行时都不同。
我也需要在 ColdFusion 中获得与“CHp”相同的结果。
最佳答案
您需要使用 ColdFusion 提供的函数,使用 toString(xxx)
将二进制表示形式转换为字符串,而不是底层 java 函数 xxx.toString()
,因为两者都会呈现不同的结果。这听起来很奇怪,但事实并非如此,java是硬类型语言,你不能简单地将二进制数据转换为像这样的字符串表示形式,refer to this post 。另外,如果您在原始 CF 代码中注意到,每次运行时的输出都会不同。
回到你的问题,你只需要做一点改变,它就可以正常工作:
<cfset key="43480170" />
<cfoutput>#toString(binaryDecode(key, "hex" ))#</cfoutput>
您可以run the code here检查两种方法之间输出的差异。
更新:
遵循 @Leigh 的有用评论使用 CharsetEncode()
执行二进制到字符串转换的推荐方法函数,代码将导致:
<cfset key="43480170" />
<cfoutput>#CharsetEncode(binaryDecode(key, "hex" ),'utf-8')#</cfoutput>
您可以查看 updated gist随着变化。
关于php - PHP 的 hex2bin 函数的 ColdFusion 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31516701/