【问题标题】:save string array in binary format以二进制格式保存字符串数组
【发布时间】:2010-01-20 14:26:09
【问题描述】:
string value1 , value1 ;
int length1 , length2 ;
System.Collections.BitArray bitValue1 = new System.Collections.BitArray(Length1);
System.Collections.BitArray bitValue2 = new System.Collections.BitArray(Length2);

我正在寻找将每个字符串转换为每个字符串定义长度的 BitArray 的最快方法(如果字符串大于定义的长度并且如果字符串大小更小,则应修剪字符串,其余位将填充为 false)然后把这两个字符串放在一起,写成一个二进制文件。

编辑: @dtb:一个简单的例子可以像这样 value1 = "A" ,value2 = "B" and length1 =8 and length2 = 16 结果将是 010000010000000001000010 前 8 位来自“A”,接下来的 16 位来自“B”

【问题讨论】:

  • 为什么需要 BitArray?
  • 如果有其他方法,我不需要位数组。但考虑到长度可以是任意数字(可能是 2 位)
  • 字符串的内容是什么?您能否附上一些代码来进一步解释您要为我们的 SO'ers 实现什么?
  • 字符串可以包含任何内容(整数、布尔值、字符串...但都转换为字符串)
  • 你能发布一个输入和预期输出的例子吗?

标签: c# string binaryfiles


【解决方案1】:
        //Source string
        string value1 = "t";
        //Length in bits
        int length1 = 2;
        //Convert the text to an array of ASCII bytes
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(value1);
        //Create a temp BitArray from the bytes
        System.Collections.BitArray tempBits = new System.Collections.BitArray(bytes);
        //Create the output BitArray setting the maximum length
        System.Collections.BitArray bitValue1 = new System.Collections.BitArray(length1);
        //Loop through the temp array
        for(int i=0;i<tempBits.Length;i++)
        {
            //If we're outside of the range of the output array exit
            if (i >= length1) break;
            //Otherwise copy the value from the temp to the output
            bitValue1.Set(i, tempBits.Get(i));                
        }

我要继续说下去,这假设 ASCII 字符,所以任何高于 ASCII 127 的字符(例如简历中的 é)都会吓坏并可能返回 ASCII 63,即问号。

【讨论】:

  • 谢谢 cheris 我稍微编辑了代码,现在运行良好。顺便说一句,我发现这可能有助于其他想要保存二进制数据的人:codeproject.com/KB/cs/bitstream.aspx
【解决方案2】:

将字符串转换为其他字符串时,您需要考虑要使用的编码。这是一个使用 UTF-8 的版本

bitValue1 = System.Text.Encoding.UTF8.GetBytes(value1, 0, length1);

编辑 嗯...看到您正在寻找的是 BitArray 而不是 ByteArray,这可能对您没有帮助。

【讨论】:

  • length1 是位数。
【解决方案3】:

由于这不是一个非常明确的问题,我还是会试一试,

使用 System.IO; 使用 System.Runtime.Serialization; 使用 System.Runtime.Serialization.Formatters.Binary; 公共静态无效 RunSnippet() { 字符串 s = "123"; byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(s); System.Collections.BitArray bArr = new System.Collections.BitArray(b); Console.WriteLine("bArr.Count = {0}", bArr.Count); for(int i = 0; i

这就是你想要达到的目标吗?

希望这会有所帮助, 最好的祝福, 汤姆。

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2011-04-26
    • 2013-10-24
    相关资源
    最近更新 更多