将十六进制字符串转换为 base64 [英] Convert a hex string to base64

查看:122
本文介绍了将十六进制字符串转换为 base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

所以我明白了,现在如何将 hexString 转换为 base64 字符串?
我试过这个,得到了错误:

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?

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

我试过这个,但它在第一个返回无法将类型'byte []'隐式转换为'string'"行,然后是参数 1:无法从 'string' 转换为 'byte[]'".

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[]'".

推荐答案

您首先需要将您的十六进制字符串转换为字节数组,然后您可以将其转换为 base-64.

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

要将十六进制字符串转换为 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());
 }

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

这篇关于将十六进制字符串转换为 base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆