hex2bin 函数的 ColdFusion 替代方案 PHP

ColdFusion alternative for hex2bin function PHP

我想解码十六进制编码的二进制字符串;它将通过使用 PHP 的 hex2bin 函数来工作。但我在 ColdFusion 中需要同样的东西。

PHP

 $key="43480170";

 echo hex2bin($key);

输出:CHp

我试过下面的代码。但是这个 ColdFusion 代码没有给我在 PHP;

中得到的结果

ColdFusion

<cfset key="43480170" />

<cfoutput>#binaryDecode(key, "hex" ).toString()#</cfoutput>

输出:每次运行时都不一样。

我也需要在 ColdFusion 中获得与“CHp”相同的结果。

你们很亲近。这应该可以解决问题。

<cfset key="43480170">
<cfoutput>#toString(binaryDecode(key, "hex" ))#</cfoutput>

Returns 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 on the recommended way to perform a binary to string conversion using the CharsetEncode() 函数的有用注释之后,代码将导致:

<cfset key="43480170" />
<cfoutput>#CharsetEncode(binaryDecode(key, "hex" ),'utf-8')#</cfoutput>

您可以检查 updated gist 的变化。