Skip to main content
April 12, 2012
Question

How do you convert hexadecimal to binary?

  • April 12, 2012
  • 1 reply
  • 3720 views

Hello,

I am working on a project where I need to convert a hexadecimal packet to binary.  It is looking like I would use the BinaryEncode function, but I wasn't really sure if that was the right way to go about it or not.

For instance, I need to convert '01DD6300000C0E1012' to '000000011101110101100011000000000000000000001100000011100001000000010010'.

I had thought it would be straight forward such.

<cfset myHex = "01DD6300000C0E1012">

<cfset myBinary = BinaryDecode(myHex, "hex")>

<cfoutput>

    <h2>

        myHex = #myHex#<br />

        myBinary = #myBinary#

    </h2>

</cfoutput>

However, I end up getting the following error.

ByteArray objects cannot be converted to strings.

The error occurred in C:\inetpub\wwwroot\playground\hexIT.cfm: line 17

15 :     <h2>

16 :         myHex = #myHex#<br />

17 :         myBinary = #myBinary#

18 :     </h2>

19 : </cfoutput>

I was expecting that the result was going to be a string of data and not a ByteArray.

Is there a better way to go about this?

Best regards

KR

    This topic has been closed for replies.

    1 reply

    BKBK
    Community Expert
    Community Expert
    April 12, 2012

    The set of functions you want is: inputBaseN, formatBaseN. For example,

    <cfset myHex                 = "1DD630000C0E1012">

    <cfset myHexInBase10  = inputBaseN(myHex,16)>

    <cfset myHexInBase2    = formatBaseN(myHexInBase10,2)>

    <cfoutput>

        <h2>

        myHex = #myHex#<br />

        myBinary = #myHexInBase2#

        </h2>

    </cfoutput>

    However, I did use a smaller hex. It seems your original number is larger than ColdFusion's range.

    April 12, 2012

    Hello,

    Thanks.  That helped tremendously.   The good news is that it came to my attention after your reply, that we really only need to parse part of the hex value, so this works out fine.  The other news is that it looks like I then have to convert the binary value to 8-bit decimal.

    How would I go about that part?

    Best regards,

    KR

    Inspiring
    April 12, 2012

    Can you give an example of the expected results?