在C#转换字节数组字符串,然后再返回 [英] Converting byte array to string and back again in C#

查看:106
本文介绍了在C#转换字节数组字符串,然后再返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里的交易:我试图打开一个文件(从字节),将其转换为字符串,这样我就可以在标题中的一些元数据的混乱,将其转换回字节,并保存它。我运行到现在的问题是这段代码。当我比较这就是被来回转换(但不以其他方式修改)原来的字节数组字符串,它是不平等的。我怎样才能使这项工作?

So here's the deal: I'm trying to open a file (from bytes), convert it to a string so I can mess with some metadata in the header, convert it back to bytes, and save it. The problem I'm running into right now is with this code. When I compare the string that's been converted back and forth (but not otherwise modified) to the original byte array, it's unequal. How can I make this work?

public static byte[] StringToByteArray(string str)
{
    UTF8Encoding encoding = new UTF8Encoding();
    return encoding.GetBytes(str);
}

public string ByteArrayToString(byte[] input)
{
    UTF8Encoding enc = new UTF8Encoding();
    string str = enc.GetString(input);
    return str;
}

下面是我是如何对它们进行比较。

Here's how I'm comparing them.

byte[] fileData = GetBinaryData(filesindir[0], Convert.ToInt32(fi.Length));
string fileDataString = ByteArrayToString(fileData);
byte[] recapturedBytes = StringToByteArray(fileDataString);
Response.Write((fileData == recapturedBytes));



我敢肯定,这是UTF-8,使用:

I'm sure it's UTF-8, using:

StreamReader sr = new StreamReader(filesindir[0]);
Response.Write(sr.CurrentEncoding);



返回System.Text.UTF8Encoding。

which returns "System.Text.UTF8Encoding".

推荐答案

尝试在编码类,它为您提供了各种编码的情况下,静态函数。你不应该需要实例化编码只是转换到/从一个字节数组。你如何比较在代码中的字符串?

Try the static functions on the Encoding class that provides you with instances of the various encodings. You shouldn't need to instantiate the Encoding just to convert to/from a byte array. How are you comparing the strings in code?

修改

您所比较的数组,而不是字符串。他们是不平等的,因为它们指的是两个不同的阵列;使用 == 运营商将只比较它们的引用,而不是它们的值。你需要检查数组的每个元素,以确定它们是否是等价的。

You're comparing arrays, not strings. They're unequal because they refer to two different arrays; using the == operator will only compare their references, not their values. You'll need to inspect each element of the array in order to determine if they are equivalent.

public bool CompareByteArrays(byte[] lValue, byte[] rValue)
{
    if(lValue == rValue) return true; // referentially equal
    if(lValue == null || rValue == null) return false; // one is null, the other is not
    if(lValue.Length != rValue.Length) return false; // different lengths

    for(int i = 0; i < lValue.Length; i++)
    {
        if(lValue[i] != rValue[i]) return false;
    }

    return true;
}

这篇关于在C#转换字节数组字符串,然后再返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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