问题
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