Convert fixed size buffer (byte array) to string

c# byte array to string
c# fixed size array in struct
convert byte array to string c# without encoding
c byte array to string hex
cannot convert byte() to string c#
c# fixed size byte array
convert single byte to string c#
c byte array to string hex

I've seen several related topics on SO and other forums, but haven't found a workable answer to my question.

Here's my code:

[StructLayout(LayoutKind.Explicit, Size = 128)]
internal unsafe struct Frame
{
    [FieldOffset(0)]
    public fixed byte Bytes[128];

    [FieldOffset(0)]
    public long Low;

    [FieldOffset(128 - sizeof(long))]
    public long High;
}

unsafe private void button32_Click(object sender, EventArgs e)
{
    Frame frame;

    // ERROR: Error 15  You cannot use the fixed statement to take the address of an already fixed expression
    fixed (byte* ptr = frame.Bytes)
    {

    }

    // ERROR
    Console.Write(System.Text.Encoding.ASCII.GetString(frame.Bytes, 0, 128));
    frame.Low = 1234;
    //Console.Write(System.Text.Encoding.ASCII.GetString(frame.Bytes));
    frame.High = 5678;
    //Console.Write(System.Text.Encoding.ASCII.GetString(frame.Bytes));
}

Just wrap the struct into another class to eliminate the fixed pointer issue. This creates the struct inside the memory frame of the new class. Then convert the fixed array to a byte[] to eliminate the GetString() issue. Maybe this helps?

namespace test
{
        [StructLayout(LayoutKind.Explicit, Size = 128)]
        internal unsafe struct Frame
        {
            [FieldOffset(0)]
            public fixed byte Bytes[128];

            [FieldOffset(0)]
            public long Low;

            [FieldOffset(128 - sizeof(long))]
            public long High;                
        }

    internal class NewClass
    {
        public Frame FixedBytesArray;
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            unsafe
            {
                NewClass NewType = new NewClass();
                NewType.FixedBytesArray.High = 12345;
                NewType.FixedBytesArray.Low = 6789;


                fixed (byte* ptr = NewType.FixedBytesArray.Bytes)
                {
                    byte[] bytes = new byte[128];
                    int index = 0;
                    for (byte* counter = ptr; *counter != 0; counter++)
                    {
                        bytes[index++] = *counter;
                    }

                    Console.Write(System.Text.Encoding.ASCII.GetString(bytes, 0, 128));
                }
            }    
        }
    }
}

https://social.msdn.microsoft.com/Forums/vstudio/e, The only restriction is that the array type must be bool , byte , char , short , int , long , sbyte , ushort , uint , ulong , float , or double . C# Copy. private  Since an ArrayBuffer is, in fact, a byte array, this conversion requires that both ends agree on how to represent the characters in the String as bytes. You probably have seen this "agreement" before: it is the String's character encoding (and the usual "agreement terms" are, for example, Unicode UTF-16 and iso8859-1).

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);
}


static byte[] StringToByteArray(string str, int length) 
{
    return Encoding.ASCII.GetBytes(str.PadRight(length, ' '));
}  

Fixed Size Buffers, In the example below, I'm trying to convert a fixed byte array to a string. ERROR​: You cannot use fixed size buffers contained in unfixed 76. 76 silver badges. 131. 131 bronze badges. new string ( (sbyte*) frame.Bytes) should work if you are using ASCII only (or perhaps the overload taking start and length). – leppie Jan 2 '14 at 8:18. Nice and simple. However, any value is possible in the byte array. – IamIC Jan 2 '14 at 8:21.

The compiler error states it very well: you were trying to fix something that already has been fixed...

You only fix the reference when assigning a pointer. This prevents the reference to be moved to somewhere else in memory (garbage collection) then expected - using MS words, the reference becomes 'pinned'.

In your case, you don't need to fix your struct when defining but when referencing your pointer fix the 'source' by applying the "fixed" statement (this part of your code is correct).

Solution should be to remove the fix statements from your struct. If you like to read some about it: MSDN - fixed Statement (C# Reference)

Fixed Byte Array to String - C# / C Sharp, Learn to convert a C# byte array to string in C# and . The BitConverter class has a static overloaded GetBytes method that takes an integer, double or string utfString = Encoding.UTF8.GetString(bytes, 0, bytes.Length);. Now if we want to do the conversion in the other direction, that is from a byte array to a string, then this can simply be done as follows. string converted = Encoding.UTF8.GetString(buffer, 0, buffer.Length); As you can see, C# makes it very easy to convert strings to and from byte arrays. I hope this helped you.

Nothing of the above works for me, so I created another solution:

StringBuilder sb = new StringBuilder();
fixed (byte* b = fixedByteArray)
{
  for (int i = 0; i < knownLengthOfByteArray; i++)
  {
    sb.Append((char)b[i]);
  }
}
return sb.ToString();

Works for ANSI strings.

Convert Byte Array To String In C#, Unicode, and each Unicode character is actually 2 bytes in size. When ASCII characters are converted to a Byte array, every other byte in the array must convert the Byte buffer's binary contents to a Unicode string ourselves, NOTE You can assign a string to a Byte array only if the array is dynamic, not if it is fixed in size. string convert = "This is the string to be converted"; // From string to byte array byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert); // From byte array to string string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length); improve this answer. edited Nov 2 '15 at 17:46. answered Jul 25 '12 at 16:55. 53 silver badges.

Microsoft Visual Basic 6.0 Developer's Workshop, you try to convert a Byte Array object to String, you still have a character set ASCII conversion. Encoding.ASCII .GetString(byteArray, 0, byteArray.Length);  The answers referring to simply calling array() are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations.

How convert byte array to string C# VB.Net asp.net, Please consider implementing support for fixed-size, "inline" arrays in struct definitions, as in C/C++, or in C#'s Fixed Size Buffers. byte[13] ), this may improve performance by eliminating lots of small array/string heap allocations. BROKEN!!! public static byte* Convert(ArraySegment<byte> value, byte*  String can be converted do byte array in few different ways, due to the following fact: .NET supports Unicode, and Unicode standardizes several difference encodings called UTFs. They have different lengths of byte representation but are equivalent in that sense that when a string is encoded, it can be coded back to the string, but if the string

Support for fixed-size / inline arrays · Issue #303 · microsoft/bond , buffers, fixed-size, Fixed-size buffers built-in types (see predefined types) byte arrays conversions to, BitConverter converting MemoryStream to, Encoding to byte arrays byte type, Numeric Types, 8- and 16-Bit Integrals C C format string,  Convert a string to a byte array and then reverse the conversion. A string can be converted into a byte array. Strings are stored with two bytes per character. ASCII only allows one byte per character. Conversion problems. With some ASCII conversions, we can lose data. With Encoding.ASCII.GetBytes, and GetString, we perform this conversion.

Comments
  • new string((sbyte*) frame.Bytes) should work if you are using ASCII only (or perhaps the overload taking start and length).
  • Nice and simple. However, any value is possible in the byte array.
  • What do you mean by any value? Using something else than ASCII?
  • I mean the byte array is binary. It can contain any value. I only want to view it as a string in order to inspect the fact of changes (debugging purposes).
  • The debugger display attribute would be a nicer option here, IMO.
  • U mean to create a byte[]? Think this doesn't work because though an array is a reference type all its values are value type. And each value type has its own reference. So an array contains references to their values. But we just supply the first adress of the array and so the compiler doesn't know where to find the values.
  • I hope you find it useful. It's a really powerful, efficient way of doing what is often impossible, such as casting floats to int, etc.
  • Thanks. Console.Write(GetString(frame.Bytes)); doesn't work as I think it's expecting a pointer-compliant method.
  • The fixed statement has subtle advantages, such as automatically creating the structure without my needing to do so explicitly, which overcomes other issues such as the initialization of structs.
  • And why do you use the same fieldoffset for two different attributes?
  • I get the double-fixing, but not sure how to resolve it. The byte[] is represented as an array of longs, hence the "duplicate address".
  • Sorry, just trying to understand. From my point of view you assign no reference to the field but their explicit location in memory. You reserve a block of 128 Byte in memory for your struct. Now you explicitly organize this area by explicitly tellin the compiler where in this memoryblock to create the field. Are you sure you are not overwriting your byte array?
  • Array starts at pos 0. Another field is created at the same place. So there is nothing beeing overridden? My guess is that you override the byte array (which was fixed in size!) with a Long field which memory area is still fixed but now in location.