Tim Svensson
Tim Svensson

Reputation: 37

C# byte array into variables

I have a byte array and I would like to get values from it into variables. I know the values format like string, unsigned int etc.

byte[] buffer = File.ReadAllBytes("binarydata.bin");
string value1 = ???
uint16 value2 = ???
string value3 = ???
uint32 value4 = ???

How can i assign the values? I know that the first value is a string of 8, i know the second value is a usigned 16bit int, and the third value is a string of 12 and the forth is a unsigned 32 bit int.

Upvotes: 1

Views: 1962

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

You could simply use BinaryReader

Reads primitive data types as binary values in a specific encoding

Example

using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
    var aspectRatio = reader.ReadSingle();
    var tempDirectory = reader.ReadString();
    var autoSaveTime = reader.ReadInt32();
    var showStatusBar = reader.ReadBoolean();

    Console.WriteLine("Aspect ratio set to: " + aspectRatio);
    Console.WriteLine("Temp directory is: " + tempDirectory);
    Console.WriteLine("Auto save time set to: " + autoSaveTime);
    Console.WriteLine("Show status bar: " + showStatusBar);
}

Update from xanatos

ReadString Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.

Upvotes: 3

user9729877
user9729877

Reputation:

You can use BinaryReader ,this example writes data as binary. After reads binary data and assigns to variables.

using System;
using System.IO;

class ConsoleApplication
{
const string fileName = "AppSettings.dat";

static void Main()
{
    WriteDefaultValues();
    DisplayValues();
}

public static void WriteDefaultValues()
{
    using (BinaryWriter writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
    {
        writer.Write(1.250F);
        writer.Write(@"c:\Temp");
        writer.Write(10);
        writer.Write(true);
    }
}

public static void DisplayValues()
{
    float aspectRatio;
    string tempDirectory;
    int autoSaveTime;
    bool showStatusBar;

    if (File.Exists(fileName))
    {
        using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
        {
            aspectRatio = reader.ReadSingle();
            tempDirectory = reader.ReadString();
            autoSaveTime = reader.ReadInt32();
            showStatusBar = reader.ReadBoolean();
        }

        Console.WriteLine("Aspect ratio set to: " + aspectRatio);
        Console.WriteLine("Temp directory is: " + tempDirectory);
        Console.WriteLine("Auto save time set to: " + autoSaveTime);
        Console.WriteLine("Show status bar: " + showStatusBar);
        }
    }
}

Upvotes: 0

Related Questions