【问题标题】:Write string to fixed-length byte array in C#在 C# 中将字符串写入固定长度的字节数组
【发布时间】:2010-04-07 20:19:17
【问题描述】:

不知何故无法通过谷歌搜索找到它,但我觉得它必须很简单......我需要将字符串转换为固定长度的字节数组,例如将“asdf”写入byte[20] 数组。数据正在通过网络发送到需要固定长度字段的 c++ 应用程序,如果我使用 BinaryWriter 并一个一个地写入字符,然后通过写入 '\0' 来填充它,它可以正常工作次数。

有没有更合适的方法来做到这一点?

【问题讨论】:

    标签: c# string bytearray


    【解决方案1】:
    static byte[] StringToByteArray(string str, int length) 
    {
        return Encoding.ASCII.GetBytes(str.PadRight(length, ' '));
    }   
    

    【讨论】:

    • 这将用空格(0x20)填充缓冲区,而不是海报提到的空字符(0x0)。否则这很好。
    • 如果文本长于length,这将不起作用。如果我们有 50 字节长的字符串,并且我们将这个方法与 length 参数 30 一起使用,我们得到 50 字节长的字节数组而不是 30。
    【解决方案2】:

    这是一种方法:

      string foo = "bar";
    
      byte[] bytes = ASCIIEncoding.ASCII.GetBytes(foo);
    
      Array.Resize(ref bytes, 20);
    

    【讨论】:

      【解决方案3】:

      怎么样

      String str = "hi";
      Byte[] bytes = new Byte[20];
      int len = str.Length > 20 ? 20 : str.Length;
      Encoding.UTF8.GetBytes(str.Substring(0, len)).CopyTo(bytes, 0);
      

      【讨论】:

      • @Reed 好电话。我已经修复了这个错误。
      【解决方案4】:

      您可以使用Encoding.GetBytes

      byte[] byteArray = new byte[20];
      Array.Copy(Encoding.ASCII.GetBytes(myString), byteArray, System.Math.Min(20, myString.Length);
      

      【讨论】:

      • 使用 System.Math.Min 是一种聪明的方法。
      【解决方案5】:

      也许有不安全的代码?

      unsafe static void Main() {
          string s = "asdf";
          byte[] buffer = new byte[20];
          fixed(char* c = s)
          fixed(byte* b = buffer) {
              Encoding.Unicode.GetBytes(c, s.Length, b, buffer.Length);
          }
      }
      

      (缓冲区中的字节默认为 0,但您始终可以手动将它们归零)

      【讨论】:

        【解决方案6】:
        Byte[] bytes = new Byte[20];
        String str = "blah";
        
        System.Text.ASCIIEncoding  encoding = new System.Text.ASCIIEncoding();
        bytes = encoding.GetBytes(str);
        

        【讨论】:

        • 最后一行将用新的数组长度 4 覆盖您的 bytes
        【解决方案7】:

        为了完整起见,LINQ:

        (str + new String(default(Char), 20)).Take(20).Select(ch => (byte)ch).ToArray();
        

        对于变体,这个 sn-p 还选择将 Unicode 字符直接转换为 ASCII,因为前 127 个 Unicode 字符被定义为与 ASCII 匹配。

        【讨论】:

          【解决方案8】:

          FieldOffset,也许吧?

          [StructLayout(LayoutKind.Explicit)]
          public struct struct1
          {
              [FieldOffset(0)]
                  public byte a;
              [FieldOffset(1)]
                  public int b;
              [FieldOffset(5)]
                  public short c;
              [FieldOffset(8)]
                  public byte[] buffer;
              [FieldOffset(18)]
                  public byte d;
          }
          

          (c)http://www.developerfusion.com/article/84519/mastering-structs-in-c/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-01-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多