# C# Decomposing fixed byte[] in elements

## Recommended Posts

Some weeks ago I was asking how to fill a fixed byte[] array with values (floats, ints, etc). Now I need the opposite: I have to parse that array, received from the client, into values. Seems that BitConverter cant accept fixed byte[] as parameter, how can I convert it to something usable bit BitConverter?

##### Share on other sites

The term you are looking for is either serializing/deserializing, or more generically marshalling.

Have you tried this technique? I don't do C#, so I don't know if this is .NET-specific, or if Unity's subset of it offers these features as well. https://stackoverflow.com/a/28761634/2984949

##### Share on other sites

The techniques I posted in the last thread work bidirectionally.

You can convert the fixed byte array to an IntPtr for use with Marshal with: new IntPtr(fixedArray);

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
class Program
{
static unsafe void Main(string[] args)
{
var buffer = new MyBuffer();

buffer.fixedBuffer[3] = 1;
buffer.fixedBuffer[4] = 0xC8;

// section of the array that will be used now contains:
// 00 00 00 01 C8 00 00 00
// ^^^^^^^^^^^ ^^^^^^^^^^^
// Foo         Bar
// Little Endian will be used on Little Endian computers (the majority of them)
// outputs will be:
// Foo = 0x01000000 (16777216)
// Bar = 0x000000C8 (2.802598E-43)

var blarg = Marshal.PtrToStructure<Blarg>(new IntPtr(buffer.fixedBuffer));

Console.WriteLine(blarg.Foo);
Console.WriteLine(blarg.Bar);

// To put values back in:
blarg.Foo = 1;
blarg.Bar = 1;

Marshal.StructureToPtr(blarg, new IntPtr(buffer.fixedBuffer), false);

for (int i=0; i<8; ++i)
{
Console.Write(\$"{buffer.fixedBuffer[i]:X2} ");
}
Console.WriteLine();
}
}

[StructLayout(LayoutKind.Sequential)]
struct Blarg
{
public int Foo;
public float Bar;
}

internal unsafe struct MyBuffer
{
public fixed byte fixedBuffer[128];
}
}

If you want to just convert the fixed byte[] to a normal byte[] you can copy the entire thing to a managed array using Marshal.Copy and then use normal C# byte[] techniques like MemoryStream, BinaryReader, StreamReader, BitConverter, etc.

Edited by Nypyren

## Create an account

Register a new account

• 9
• 56
• 18