Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将包含1和0的字符串保存到bin文件?_C#_Bin - Fatal编程技术网

C# 如何将包含1和0的字符串保存到bin文件?

C# 如何将包含1和0的字符串保存到bin文件?,c#,bin,C#,Bin,嗨,我有字符串str=“1010101010101010”来自file.txt,它正好包含16个符号:0和1。这只是一个示例,str可以有16个以上的符号:8,16,24,32,40。。。我想把它保存到file.bin。保存文件后,file.bin的大小必须为2B(在本例中)。 我试着用 File.WriteAllText(path, str); 但是我的文件比我想要的大。有人能帮我吗?你可以试试这样的东西。这适用于您发布的16位。如果您有更多数据,您可能希望一次读取32位数据并进行转换。但这

嗨,我有字符串str=“1010101010101010”来自file.txt,它正好包含16个符号:0和1。这只是一个示例,str可以有16个以上的符号:8,16,24,32,40。。。我想把它保存到file.bin。保存文件后,file.bin的大小必须为2B(在本例中)。 我试着用

File.WriteAllText(path, str);

但是我的文件比我想要的大。有人能帮我吗?

你可以试试这样的东西。这适用于您发布的16位。如果您有更多数据,您可能希望一次读取32位数据并进行转换。但这应该让你开始

void Main()
{
    string path = @"g:\test\file.bin";
    string str="1010101010101010";

    //Convert string with 16 binary digits to a short (2 bytes)
    short converted = Convert.ToInt16(str, 2);

    //Convert the short to a byte array
    byte[] bytes = BitConverter.GetBytes(converted);

    //Write the byte array to a file
    using (var fileOut = new System.IO.FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
    {
        fileOut.Write(bytes, 0, bytes.Length);
    }
}

当然您必须一次执行8位,解析数字(手动或使用
Convert.ToByte(substr,2)
),然后像这样写入您得到的字节。您试图写入一个二进制文件,因此写入文本文件不起作用也就不足为奇了:)@AlexK。我想他只是说他可以在输出上有多个字节-2,4,6。。。但输入字符串仍然只是一个二进制数字字符串。