将十六进制代码转换为文本 c#

本文关键字:文本 转换 十六进制 代码 | 更新日期: 2023-09-27 18:31:23

尝试转换十六进制代码,如"4557415049534341"将文本设置为"EWAPISCA"

代码 :

  private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog op1 = new OpenFileDialog();
        op1.Filter = "BinFiles (.bin)|*.bin";
        if (op1.ShowDialog() == DialogResult.OK)
        {
            BinaryReader br = new BinaryReader(File.OpenRead(op1.FileName));
            string armorValues = null;
            for (int i = 0x0019fcad; i <= 0x0019fcb4; i++)
            {
                br.BaseStream.Position = i;
                armorValues += br.ReadByte().ToString("X2"); 
            }
            br.Close();
            string hex = armorValues;
            hex = hex.Replace("-", "");
            byte[] raw = new byte[hex.Length / 2];
            for (int i = 0; i < raw.Length; i++)
            {
                raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            string result = raw.ToString();
            richTextBox1.Text = result;
        }
    }

在 richTextBox1 中显示"System.Byte[]"

将十六进制代码转换为文本 c#

您应该使用某种编码将字节转换为字符串

var s = System.Text.Encoding.UTF8.GetString(byteArray);

正如这个答案所指出的:如何将字节[]转换为字符串?

请尝试此代码

static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}

谢谢

MSDN 的一个示例:

string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
    // Convert the number expressed in base-16 to an integer. 
    int value = Convert.ToInt32(hex, 16);
    // Get the character corresponding to the integral value. 
    string stringValue = Char.ConvertFromUtf32(value);
    char charValue = (char)value;
    Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
                        hex, value, stringValue, charValue);
}
/* Output:
    hexadecimal value = 48, int value = 72, char value = H or H
    hexadecimal value = 65, int value = 101, char value = e or e
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 6F, int value = 111, char value = o or o
    hexadecimal value = 20, int value = 32, char value =   or
    hexadecimal value = 57, int value = 87, char value = W or W
    hexadecimal value = 6F, int value = 111, char value = o or o
    hexadecimal value = 72, int value = 114, char value = r or r
    hexadecimal value = 6C, int value = 108, char value = l or l
    hexadecimal value = 64, int value = 100, char value = d or d
    hexadecimal value = 21, int value = 33, char value = ! or !
*/