.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Fastest -- way to move a byte array to a structure and back.

Posted By:      Posted Date: October 19, 2010    Points: 0   Category :.NET Framework

I want to encode a structure to Base64 and decode it back to a structure. What is the FASTEST way of doing this in .NET 4? FYI the structure is byte packed. The examples from the net show something like this to pack it. I was wondering if .NET 4 has grown up enough to handle binary data any faster.  

unsafe public byte[] ToRaw()
byte[] byteArray = new byte[EntityState.PDU_SIZE];
IntPtr pointer = Marshal.AllocHGlobal(EntityState.PDU_SIZE);
Marshal.StructureToPtr(this, pointer, false);
Marshal.Copy(pointer, byteArray, 0, EntityState.PDU_SIZE);
return byteArray;

unsafe public byte[] ToRaw2()
byte[] byteArray = new byte[EntityState.PDU_SIZE];
fixed (byte* ptr = byteArray)
*((EntityState*)ptr) = this;
return byteArray;


View Complete Post

More Related Resource Links

Casting byte array to structure in C# -- Exception thrown



     I am using the below function to cast the byte array to the structure.But when i do that i am getting an exception saying"Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Please help me on this ASAP.

   public VasConfig BytetoStructure(byte[] bff)
     GCHandle pinnedPacket = GCHandle.Alloc(bff, GCHandleType.Pinned);
     VasConfig vasconfig = (VasConfig)Marshal.PtrToStructure(
    return vasconfig;

Structure is as below
#region Vas Data Structure
//Vas Commands used for communication between PC client to DSP server
using System.Runtime.InteropServices;
public enum VasCommands

//This is used for identifying the first data buffer
public enum yuv_fmt
  Y = 5,
//Video formats 
//Video formats 

public enum VideoFormat
  YUV_420 = 15,

//Data stream types: Currently only video is supported

public enum DataTypes
  VIDEO = 1,

//Error Code definitions

public enum ERROR_CODE

Converting ReportDocument object into byte array ?


Hi All,

          Is it possible to convert the Report Document object as a byte array and store it in SQL , later retrieve and assing it to a report ?


Editor's Note: A Look Back As We Move Forward


Here's a look at a year's worth of coverage and changes at MSDN Magazine in response to reader requests.

Howard Dierking

MSDN Magazine January 2009

Converting a byte array to a gif


Hi there,

I am currently in the process of trying to convert a byte array into a gif format. So far I have done this:

                        byte[] gif = Convert.FromBase64String(myByteArray);
                        MemoryStream ms = new MemoryStream(gif);
                        Bitmap image = new Bitmap(ms);
                        string pathToSave = Server.MapPath("~/_temp/");
                        iconUrl = string.Format("{0}/{1}.gif", pathToSave, fileName);

When this code block executes, I get the following error:

A generic error occurred in GDI+.

I have made sure that I have the correct permissions for the _temp folder, but I am not sure if I am trying to convert "bad bytes". Could someone perhaps shed some light on this error? 

Conversion of Byte Array to Memory stream


how to convert byte array to memory stream in vb.net.

How to Pass higher Length of Byte Array to the remoting method

Dear all,I am using a windows application and the businness logic is present in the remote server.Once particular method takes bytearray as input parameter...Whenever the method call is made the function returns value .This is limited for the particular bytearray length. (4109228 bytes).If the length of bytearray crosses 4109228 bytes.I am getting an error that "input stream is not valid binary format".How to Pass higher Length of Byte Array to the remoting method... Greater than 4 MB?I believe something is missing in web.config or app.config...?What could be the issue...? Any sugesstions are welcome....ThanksRavikumar

how to split byte array

hi all,how to split byte array?for eg when i convert byte array to string it will come like as followsbytetostring="%%90,53453%%20,%%20,434234my requirement is i need to split bytearray using the string byte "%%"and need to find out hex value of each linebyte to hex i did like as followsDim strTemp1 As New StringBuilder(Bytes.Length * 2)                                    For intIndex1 = offset To offset + count - 1  'offset is 0 and count is length of the string                                        strTemp1.AppendFormat("{0:x2}", Bytes(intIndex1))                                    Nextthis function resulting the hex value of full string.I need hex value of each byte splitted with "%%"

Converting a System.Windows.Control.Image object to byte array.

Hi i need to convert a specific System.Windows.Control.Image object into an (int) array, because i'm trying to convert a silverlight application into a wpf project. private void createGi02GradBrush()<br/> {<br/> WriteableBitmap oWriteableBitmap = new WriteableBitmap(256, 256);<br/> Image oImage = new Image();<br/> oImage.Arrange(new Rect(0, 0, 256, 256));<br/> oImage.Measure(new Size(256, 256));<br/> oImage.Source = new WriteableBitmap(256, 256);<br/> Gi02GradShaderEffect oGi02GradShaderEffect = new Gi02GradShaderEffect();<br/> oGi02GradShaderEffect.pArray = oPImageBrush;<br/> oGi02GradShaderEffect.gi1GradArray = oGi1GradImageBrush;<br/> oImage.Effect = oGi02GradShaderEffect;<br/> oWriteableBitmap.Render(oImage, null);//here<br/> oWriteableBitmap.Invalidate(); <br/> this.oGi02GradImageBrush = new ImageBrush();<br/> this.oGi02GradImageBrush.ImageSource = oWriteableBitmap;<br/> } I've found some similar topics however Image object is not the same and most of its methods aren't available. Here I'm rendering a writablebitmap with a given Image object, but in wpf we need an array. oWriteableBitmap.Render(oImage, null); Any idea? Thanks. Joseph.  

write Data to Byte[ ] array

Hi All.i hava a data in string variable for example :string Data = "0M8R4KGxGuEAAAAAAAAAAAAAAAAAAAAAPgADAP7/"and i want to convert this data to binary format so that i can insert this data to Image data field in Database .. can u please give me the solution.Thanks in advance

Move page in Site Content and Structure alters revision history and makes old content available


This sounds bizzare, I tried it on an OOTB publishing site.

I have a page X in site A. Page X has version 1.0 and 2.0 approved and published, no minor versions anywhere. I choose to move page X to site B. Page X now has revision history version 1.0 (published and available) and version 1.1, which is exactly the same as version 2.0 but no longer visible to the outside world.

So the first problem is that moving a page makes a previously published and overwritten version of the page content available again. If I publish the page it goes to version 2.0, but I have to remember to do this. Also because I approve the page, my user id is associated with the publication of the content (which is sorta ok) but the original author of version 2.0 has now presumably been lost to the ether ... or the green swirling icon of death.

But I don't publish page X because I think "oops I meant to move page Y" and move it back to site A, without first publishing version 1.1. Now I have version 0.1 and 0.2. 0.1 matches the original version 1.0, and version 0.2 matches the original version 2.0, however the best bit is that the timestamps are such that version 0.1 is now checked in after version 0.2.

I then publish the page, I now have version 0.1 and 1.0, where 0.1 matches the original version

Converting byte[] array to Int32


Hi guys,

I am trying to read in a binary file created by a legacy VBA application.

One of the sections of the file is a date, which was written out as a four byte segment equivalent a VBA long with value 40451.

In the binary array this is represented as: 33, 67, 101, 135

If I convert the binary array back into a long in VBA I get the number 40451 again.

However, if I create a four byte array in C# and try and convert that to an Int32 using BitConverter I get the value -2023406815.

I have tried reversing the byte order but not getting anything close to 40451.

Anyone got any ideas on how to get the same value as the original VBA long?



Converting an Image/BitmapImage object into Byte Array and vice versa

Hi,  I have an requirement of developing an application (WPF) that recevies image object from WCF service.

my approch is to convert the image object into stream of bytes (Byte array) in WCF part and then send to  client application. Then client application converts the byte array back to image object.

I am not able to find right sample for my approach.

would you give me guidance and would be gr8 if you provide some samples.


How to go back after use Storyboard(move) ?



I made a button, It looks like the 'IPhone' setup button.

[    O]    ->  [ |     ]


and I make two storyboards. one is move right 100 pixel (X Property), and another is move back original Position.

1)   O                          [Init]    

2)               O              [storyboard1], move X +100

3)   O                          [storyboard2], move X 0


but 2) button position was not hold on.

so I used 'Fillhavior = Stop' and 'Storyboard1.Completed += EventFunc'.

EventFunc { O.renderTransform = new TranslateTransform(100, 0); }

It's so good. but I know that I have a problem.



It's a 'storyboard2 problem'..... It has an error, I think It's not same Position when EventFunc finished !!



plz help me, how to use rectang

WPF: displaying streaming\live video from the byte array


Hi All,


I am getting the video in chunks of bytes. When i get all the bytes, then i write them to a file and give a a source to media element and that works fine.

But what i want is that I don't have to wait for all the bytes and i can start showing the video as soon as i receive the first chunk of bytes and then the video should continue as i get the secong chunk of bytes and so on. So the video should keep on streaming and appear as live.

Can someone help me out here?




WCF Hosted in IIS Gives System.ServiceModel.CommunicationException When transfering large byte array


I have a WCF service hosted in IIS that takes a byte array. If I send a small byte array the service works, if I send a large (282, 624) byte array the service fails.

I have tried increasing values etc in the config files and nothing seems to work. Any help would be greatly appreciated. Thanks

The config files are as follows:


<?xml version="1.0"?>
    <add key="GetDataFromServer" value="False"/>
    <add key="UseWpfService" value="True" />
     <add name="ServerEntities" connectionString="metadata=res://*/Server.csdl|res://*/Server.ssdl|res://*/Server.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=XPS1;Initial Catalog=TestServer;Integrated Security=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />
      <!-- This section defines the logging configuration for My.Application.Log -->

Converting a binary file to byte array


Hi Everyone-

I'm retrieving a binary file from the database, a .pdf file that I would like to let the user open and view.  From what I can tell, there are two steps to do this: 

1. Convert binary file to byte array  

2. Convert byte array to file content 

Here's what I've got so far:

 Dim c1 = (From c In dc.Documents _
                     Where c.userID = userGuid _
                     Select New With {c.downloadName, _
                                     c.docData, _
                                     c.type, _

             Dim bArray As Byte() = CType(c1.docData("binary"), Byte())
            If bArray.Length > 0 Then
                Dim fs As System.IO.FileStream = New System.IO.FileStream("d:\xx.pdf", IO.FileMode.Create)
                fs.Write(bArray, 0, bArray.Length)
            End If

This isn't working and I'm having a heck of a time trying to find a solution.  I'm getting a blue squiggly under c1.docData in the Dim bArray line. 

What am I doing wrong?

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend