Convert a hex string to base64

≡放荡痞女 提交于 2020-01-07 09:55:20

问题


byte[] ba = Encoding.Default.GetBytes(input);
var hexString = BitConverter.ToString(ba);
hexString = hexString.Replace("-", "");
Console.WriteLine("Or: " + hexString + " in hexadecimal");

So I got this, now how would I convert hexString to a base64 string?
I tried this, got the error:

Cannot convert from string to byte[]

If that solution works for anyone else, what am I doing wrong?

edit:

 var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
 return System.Convert.ToBase64String(plainTextBytes);

I tried this, but it returns "Cannot implicitly convert type 'byte[]' to 'string'" on the first line, then "Argument 1: cannot convert from 'string' to 'byte[]'".


回答1:


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;
}


来源:https://stackoverflow.com/questions/46327156/convert-a-hex-string-to-base64

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!