Simple Functions to convert Hex2Bin, Bin2Hex, Dec2Hex, Hex2Dec, Dec2Bin, Bin2Dec in C#


//return result in specified length
public string hex2Bin(string strHex,int bit)
{
int decNumber = hex2Dec(strHex);
return dec2Bin(decNumber).PadLeft(bit,'0');
}

//return result in specified length
public string dec2Bin(int val,int bit)
{
return Convert.ToString(val, 2).PadLeft(bit,'0');
}


    public string hex2Bin(string strHex)

    {

        int decNumber = hex2Dec(strHex);

        return dec2Bin(decNumber);

    }

    public string bin2Hex(string strBin)

    {

        int decNumber = bin2Dec(strBin);

        return dec2Hex(decNumber);

    }

 

    private string dec2Hex(int val)

    {

        return val.ToString("X");

        //return Convert.ToString(val,16);

    }

 

    private int hex2Dec(string strHex)

    {

        return Convert.ToInt16(strHex, 16);

    }

    private string dec2Bin(int val)

    {

        return Convert.ToString(val, 2);

    }

    public int bin2Dec(string strBin)

    {

        return Convert.ToInt16(strBin, 2);

    } 

 

Cheers !!!