简体   繁体   中英

Use the data in a c# byte array

I have an image, including image header, stored in ac# byte array (byte []).

The header is at the beginning of the byte array. If I put the header in a struct (as I did in c++) it looks like this:

typedef struct RS_IMAGE_HEADER
{
   long HeaderVersion;
   long Width;
   long Height;
   long NumberOfBands;
   long ColorDepth;
   long ImageType;
   long OriginalImageWidth;
   long OriginalImageHeight;
   long OffsetX;
   long OffsetY;
   long RESERVED[54];
   long Comment[64];

} RS_IMAGE_HEADER;

How can I do it in c#, how can I get and use all the data in the image header (that stored in the beginning of the byte array)?

Thanks

Structs are perfectly fine in C#, so there should be no issue with the struct pretty much exactly as you've written it, though you might need to add permission modifiers such as public . To convert byte arrays to other primitives, there are a very helpful class of methods that include ToInt64() that will help you convert an array of bytes to another built in type (in this case long ). To get the specific sequences of array bytes you'll need, check out this question on various techniques for doing array slices in C#.

The easiest way is to create an analog data structure in c#, I won't go into that here as it is almost the same. An example to read out individual the bytes from the array is below.

int headerVersionOffset = ... // defined in spec
byte[] headerVersionBuffer = new byte[sizeof(long)];
Buffer.BlockCopy(imageBytes, headerVersionOffset, headerVersionBuffer, 0, sizeof(long));
//Convert bytes to long, etc.
long headerVersion = BitConverter.ToInt64(headerVersionBuffer, 0);

You would want to adapt this to your data structure and usage, you could also accomplish this using a stream or other custom data structures to automatically handle the data for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM