2

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.

lambypie
  • 471
  • 1
  • 12
  • 35
  • 1
    What do you mean 'it is not working'? Do you get an error? Results not what you expected? – Scott Stroz Jul 20 '15 at 12:39
  • I didnt get the value expected. I meant I am getting a different value in PHP and Coldfusion. – lambypie Jul 20 '15 at 12:49
  • 1
    *Different every time when run it.* FWIW, that is because calling `toString()` on the byte array returns the class name and [hash code](https://en.wikipedia.org/wiki/Java_hashCode%28%29) of the byte array, not the *contents* of the array represented as a string. – Leigh Jul 20 '15 at 15:05

2 Answers2

2

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.

Community
  • 1
  • 1
Anurag
  • 1,018
  • 1
  • 14
  • 36
  • 1
    Side note, the docs recommend using charsetEncode() rather than toString() for new applications – Leigh Jul 20 '15 at 14:07
  • 1
    This is a really useful information, that slipped my mind. I think I am going to update the answer with the same. Thanks a lot @Leigh. – Anurag Jul 20 '15 at 14:40
1

You are very close. This should do the trick.

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

Returns CHp

John Whish
  • 3,016
  • 17
  • 21