.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

Converting byte[] array to Int32

Posted By:      Posted Date: October 01, 2010    Points: 0   Category :ASP.Net

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?



View Complete Post

More Related Resource Links

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 ?


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? 

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.  

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.


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?

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 Javascript/SQL array for use in asp.net VB

Hi all:   Thank you all in advance for your patience with me on this one!  This will be my first attempt at understanding code-behind. I have a JavaScript banner marquee that I am currently using in an ASP classic site.  I feed the script with banner info from a SQL array and the script runs the banners in a loop.  I want to use this on my ASP.net site conversion (from ASP classic) but I don't even know how to begin.  I have read some books, did the tutorials, but I will still need some help getting off the ground on this. Here is the ASP code.  I don;t care about the tables, rows, etc as that will be converted to CSS.  I just really need to know how to handle the array to feed the script.  Also, I am working in VB.net. I did not include the actual Javasrcipt either...  <% Set RS = Server.CreateObject("ADODB.Recordset") SQL = "SELECT xlaABMiBannersZones.bannerID, bannerfile, link FROM (xlaABMbanners INNER JOIN xlaABMiBannersZones ON xlaABMbanners.bannerid = xlaABMiBannersZones.bannerid) WHERE zoneid = '18' AND enddate >= GetDate()-1 ORDER BY enddate" set RS = conn.execute(SQL) Dim arrMini If RS.BOF AND RS.EOF Then RS.close set RS = nothing Else arrMini = RS.GetRows() End If RS.close set RS = nothing %> <div id="marqueecontainer" onmouseover="copyspeed=pausespe

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

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

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


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;


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 -->

Byte array -> String encoding

Greetings and sorry for the likely newbie question.  I also hope this is in the right forum!

What's the most "pure" way to encode a Byte array into a String?  I've performed several searches but none have yielded much insight into my particular problem.  I'm using C++, COM Interop into a VB6 application that uses a String return for socket class, but the actual issue is in the .NET native code.

  Encoding::ASCII->GetString(byteArray, 0, iNumBytes)
.. converts values >7 bits to a replacement value... and

  Encoding::UTF8->GetString(byteArray, 0, iNumBytes)
.. truncates the higher value chars from the conversion totally..

And obviously Unicode things the string is 1/2 it's actual size which makes parsing for markers in said data a real chore.  The byte streams are about 90% text and 10% binary (with markers/tags).

String containers seem to be able to do what I need them to do as manually initializing them, they get back up to the VB6 app without any problems.  It's just how to get these Byte arrays into them that's the problem.

Replacing the VB6.0 app to use something other than String would also be less than ideal as it's usage wasn't coded very managebly either and is widespread in a very, very large application.

The Byte array is from Socket class operations.  I'm unsure if there is a

Save byte array to Image with transparent background to client machine


I have an asp.net website and am exporting an image from the Report Viewer.  I have created my byte array to get the data from the report viewer and now I need to save an image with transparency to the client machine using the response headers.  I was able to do this by saving the array to the server as a bmp and then adding transparency and saving to the client as a GIF; however, the requirement has changed and now I need to do this without saving the file to the server and even though I have found several solutions using unsafe code these will not work for us because we are not allowed to use unsafe code in our environment. 


So in short I need a way to go from an array of bytes to a transparent gif and save to the client machine without using unsafe code and without saving a file to the server. 

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