在byte []和string之间进行转换的最佳方法是什么?

时间:2016-07-19 19:28:11

标签: c# type-conversion byte bytearray

我知道这个问题在堆栈溢出之前曾被问过两次,但这次我要求最有保证的方法(不改变数据值的方式)。我想从字符串转换为byte []然后再转换为字符串。我可以使用df1['ItemType1'] = df1['ItemType1'].replace(df2.set_index('ItemType2')['newType'].dropna()) ByteConverterConvertEncodingBitConverter以下代码:

HttpServerUtility.UrlTokenEncode / HttpServerUtility.UrlTokenDecode

或以下代码:

string s2 = BitConverter.ToString(bytes);   // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
{
    decBytes2[i] = Convert.ToByte(tempAry[i], 16);
}

如果你还没有得到我想要的东西,我想知道哪种方式有效,哪种无效,我想知道哪种方式应该使用。嘿,我更喜欢具有最小尺寸的字节数组,因为我将通过网络发送此数组,并且我将使用前256个字节。

1 个答案:

答案 0 :(得分:1)

  

我想从string转换为byte []然后再转换为string。

如果这是您实际尝试做的事情,您只需在发送方使用Encoding.UTF8.GetBytes(string),在接收方使用Encoding.UTF8.GetString(byte[])

private byte[] ToBytes(string message)
{
    return Encoding.UTF8.GetBytes(message);
}

private string ToString(byte[] bytes)
{
    return Encoding.UTF8.GetString(bytes);
}

这将为您提供往返,将任何字符串转换为字节,然后以最少的字节数再次转换回字符串。

这将 NOT 用于将byte []转换为字符串[],因为您需要使用Convert.ToBase64String(byte[])和{ {3}}。对于格式不正确的UTF8字符串使用Encoding.UTF8.GetString(byte[])可能会导致您在转换中丢失数据。