Convert a hex string to base64

后端 未结 2 876
北恋
北恋 2021-01-29 12:04
byte[] ba = Encoding.Default.GetBytes(input);
var hexString = BitConverter.ToString(ba);
hexString = hexString.Replace(\"-\", \"\");
Console.WriteLine(\"Or: \" + hexStri         


        
相关标签:
2条回答
  • 2021-01-29 12:42
    public string HexToBase64(string strInput)
    {
        try
        {
            var bytes = new byte[strInput.Length / 2];
            for (var i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(strInput.Substring(i * 2, 2), 16);
            }
            return Convert.ToBase64String(bytes);
        }
        catch (Exception)
        {
            return "-1";
        }
    }
    

    On the contrary: https://stackoverflow.com/a/61224900/3988122

    0 讨论(0)
  • 2021-01-29 12:46

    You first need to convert your hexstring to a byte-array, which you can then convert to base-64.

    To convert from your hexstring to Base-64, you can use:

     public static string HexString2B64String(this string input)
     {
         return System.Convert.ToBase64String(input.HexStringToHex());
     }
    

    Where HexStringToHex is:

    public static byte[] HexStringToHex(this string inputHex)
    {
        var resultantArray = new byte[inputHex.Length / 2];
        for (var i = 0; i < resultantArray.Length; i++)
        {
            resultantArray[i] = System.Convert.ToByte(inputHex.Substring(i * 2, 2), 16);
        }
        return resultantArray;
    }
    
    0 讨论(0)
提交回复
热议问题