简体   繁体   English

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

[英]Convert string to byte array c#

I obtained a byte array using File.ReadAllBytes(); 我使用File.ReadAllBytes();获得了一个字节数组File.ReadAllBytes(); and I converted it into a string ( s ). 然后将其转换为字符串( s )。

I converted my byte array to simple string using this code: 我使用以下代码将字节数组转换为简单的字符串:

        string name;
        string s;
        byte[] bytes;

        bytes = File.ReadAllBytes(name);
        foreach (byte b in bytes)
        {
            s = s + b + ".";
        }

Now s is something like "255.0.0.12.100.4.24.40.0.0.200" . 现在s类似于"255.0.0.12.100.4.24.40.0.0.200" Now I want to convert this string into a file. 现在,我想将此字符串转换为文件。 Using s.Split('.') I can get all the individual numbers. 使用s.Split('.')我可以获得所有单独的数字。 But how can I copy all the bytes into a file? 但是,如何将所有字节复制到文件中? (reconstruct the original file) (重建原始文件)

I'm a little confused by your string array being filled with File.ReadAllBytes() , as this returns a byte[] not a string[]. 我对您的字符串数组充满File.ReadAllBytes()感到有些困惑,因为这将返回byte []而不是string []。 However, that aside and focusing more on your desire to have a string[] converted to a byte[] you could do something like this (assumes your string[] is called 'str'): 但是,除了将更多的精力放在将string []转换为byte []的愿望上之外,您可以执行以下操作(假设您的string []被称为'str'):

byte[] MyByteArray = str.Select(s => Byte.Parse(s)).ToArray();

Assuming that you want to convert each string into a single byte (parse the string), here's a small program that should demonstrate how to do what you're looking for: 假设您想将每个字符串转换为一个字节(解析字符串),下面是一个小程序,该程序应演示如何执行您想要的操作:

void Main()
{
    string[] vals = new string[10];
    // populate vals...
    byte[] bytes = new byte[vals.Length];
    int i = 0;
    foreach (string s in vals)
    {
        bytes[i++] = byte.Parse(s);
    }
}

Note that there's no error handling here for the case where the string doesn't parse properly into a byte; 请注意,对于字符串未正确解析为字节的情况,此处没有错误处理。 in that situation you'll get an exception from the byte.Parse method. 在这种情况下,您会从byte.Parse方法中获得异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM