dongpo7467 2015-07-20 12:36
浏览 122
已采纳

ColdFusion替代hex2bin函数PHP

I would like to decode hexadecimal encoded binary string; It will work by using the hex2bin function of PHP. But I need the same in ColdFusion.

PHP

 $key="43480170";

 echo hex2bin($key);

Output : CHp

I have tried the below code. But this ColdFusion code not giving me the result as I got it in PHP;

ColdFusion

<cfset key="43480170" />

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

Output : Different every time when run it.

I need to get the result same as 'CHp' in ColdFusion also.

  • 写回答

2条回答 默认 最新

  • drjv5597 2015-07-20 13:43
    关注

    You need to use the ColdFusion provided function for converting binary representation to string using toString(xxx) and not the underlying java function xxx.toString() as both will render different result. This sounds strange but it is not, java is hard typed language you cannot simply convert a binary data to a string representation like that, refer to this post. Also, if you would have noticed in your original CF code the output is different every time you run it.

    Going back to your problem, you just need to make a little change and it works fine:

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

    You can run the code here to check the difference in output between the two approaches.

    Update:

    Following the useful comment by @Leigh on the recommended way to perform a binary to string conversion using the CharsetEncode() function, the code would result to:

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

    You can check the updated gist with the changes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?