Convert hex to binary

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 24 11:24:34 PDT 2015


On 04/24/2015 11:14 AM, nrgyzer wrote:
> Hi,
>
> I'm looking for a function that converts my hex-string to a binary
> representation. In Python I write the following:
>
> myHex = "123456789ABCDEF"
> myBin = myHex.decode('hex')
>
> But how to do the same in D? Is there any function?
>
> Thanks for suggestions!

Here is one way:

import std.stdio;
import std.format;

string hexToBin(string source)
{
     ulong value;
     formattedRead(source, "%x", &value);
     return format("%b", value);
}

enum string hex = "hex";

string decode(string TargetFormat)(string source)
{
     static if (TargetFormat == "hex") {
         return hexToBin(source);

     } else {
         static assert(false,
                       format("I don't know how to decode to '%s'",
                              TargetFormat));
         return "";
     }
}

void main()
{
     assert("123456789ABCDEF".decode!hex ==
            "100100011010001010110011110001001101010111100110111101111");
}

Ali



More information about the Digitalmars-d-learn mailing list