在C#中将字符串转换为字节数组

本文翻译自:Converting string to byte array in C#

I'm converting something from VB into C#. 我正在将某些东西从VB转换为C#。 Having a problem with the syntax of this statement: 该语句的语法有问题:

if ((searchResult.Properties["user"].Count > 0))
{
    profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}

I then see the following errors: 然后,我看到以下错误:

Argument 1: cannot convert from 'object' to 'byte[]' 参数1:无法从“对象”转换为“字节[]”

The best overloaded method match for 'System.Text.Encoding.GetString(byte[])' has some invalid arguments 最佳重载方法匹配'System.Text.Encoding.GetString(byte [])'有一些无效的参数

I tried to fix the code based on this post, but still no success 我试图根据这篇文章修复代码,但仍然没有成功

string User = Encoding.UTF8.GetString("user", 0);

Any suggestions? 有什么建议么?


#1楼

参考:https://stackoom.com/question/15RFF/在C-中将字符串转换为字节数组


#2楼

If you already have a byte array then you will need to know what type of encoding was used to make it into that byte array. 如果您已经有一个字节数组,那么您将需要知道使用哪种编码类型将其写入该字节数组。

For example, if the byte array was created like this: 例如,如果字节数组是这样创建的:

byte[] bytes = Encoding.ASCII.GetBytes(someString);

You will need to turn it back into a string like this: 您将需要将其重新变成这样的字符串:

string someString = Encoding.ASCII.GetString(bytes);

If you can find in the code you inherited, the encoding used to create the byte array then you should be set. 如果您可以在继承的代码中找到用于创建字节数组的编码,则应该进行设置。


#3楼

static byte[] GetBytes(string str)
{
     byte[] bytes = new byte[str.Length * sizeof(char)];
     System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     return bytes;
}

static string GetString(byte[] bytes)
{
     char[] chars = new char[bytes.Length / sizeof(char)];
     System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     return new string(chars);
}

#4楼

A refinement to JustinStolle's edit (Eran Yogev's use of BlockCopy). 对JustinStolle的编辑的改进(Eran Yogev对BlockCopy的使用)。

The proposed solution is indeed faster than using Encoding. 所提出的解决方案确实比使用编码更快。 Problem is that it doesn't work for encoding byte arrays of uneven length. 问题是它不适用于编码长度不均匀的字节数组。 As given, it raises an out-of-bound exception. 如给定的那样,它引发了越界异常。 Increasing the length by 1 leaves a trailing byte when decoding from string. 从字符串解码时,将长度增加1将留下尾随字节。

For me, the need came when I wanted to encode from DataTable to JSON . 对我来说,当我想从DataTable编码为JSON时,就产生了需求。 I was looking for a way to encode binary fields into strings and decode from string back to byte[] . 我正在寻找一种将二进制字段编码为字符串并从字符串解码回byte[]

I therefore created two classes - one that wraps the above solution (when encoding from strings it's fine, because the lengths are always even), and another that handles byte[] encoding. 因此,我创建了两个类-一个包装以上解决方案的类(当从字符串编码时就可以了,因为长度始终是偶数),另一个则处理byte[]编码。

I solved the uneven length problem by adding a single character that tells me if the original length of the binary array was odd ('1') or even ('0') 我通过添加一个字符来告诉我二进制数组的原始长度是奇数('1')还是偶数('0'),从而解决了长度不均匀的问题

As follows: 如下:

public static class StringEncoder
{
    static byte[] EncodeToBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
    static string DecodeToString(byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }
}

public static class BytesEncoder
{
    public static string EncodeToString(byte[] bytes)
    {
        bool even = (bytes.Length % 2 == 0);
        char[] chars = new char[1 + bytes.Length / sizeof(char) + (even ? 0 : 1)];
        chars[0] = (even ? '0' : '1');
        System.Buffer.BlockCopy(bytes, 0, chars, 2, bytes.Length);

        return new string(chars);
    }
    public static byte[] DecodeToBytes(string str)
    {
        bool even = str[0] == '0';
        byte[] bytes = new byte[(str.Length - 1) * sizeof(char) + (even ? 0 : -1)];
        char[] chars = str.ToCharArray();
        System.Buffer.BlockCopy(chars, 2, bytes, 0, bytes.Length);

        return bytes;
    }
}

#5楼

用这个

byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);

#6楼

First of all, add the System.Text namespace 首先,添加System.Text命名空间

using System.Text;

Then use this code 然后使用此代码

string input = "some text"; 
byte[] array = Encoding.ASCII.GetBytes(input);

Hope to fix it! 希望解决它!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值