473,738 Members | 5,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting array data

I've never done this in C# so I don't know what the appropriate way of doing
it is.

I've got an array of bytes and I need to convert the array into "usable"
data. For example, the first 4 bytes need to be converted to an enum. The
next 4 bytes to a 32-bit int. And so on. I'm basically populating a struct
with the data. How does one do this in C#?

Thanks.

Pete

--
http://www.petedavis.net
Nov 15 '05 #1
3 2341
pete, i'm not sure on your question, but i'll try to answer what i think
you're asking. please correct me if i'm not answering the right question :)

are you asking about doing the actual byte arithmetic or the best way to
access the array? if you're coming from a c background and you want to use
consecutive array elements as "memory chunks", it's not quite so nice. i
think your best bet is going to be a simple walk of the array, and using
the standard shift operators like c has. for instance, to convert 4 bytes
of a byte array to an int, you could write a simple routine:

public int ByteToInt(byte [ ] b, int startIndex)
{
int i = 0;
for(int j = 0; j < 4; j++)
i = (i << 8) + b[ j + startIndex ];
return i;
}

then you can use that to loop through all the bytes in the array...let me
know if i can help or if that's not what you're lookin for....

jeff.

--

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all responses to this
message are best directed to the newsgroup/thread from which they
originated.

Nov 15 '05 #2
There are several approaches you can take:

Take a look at these .NET Framework classes:

System.IO.Binar yReader -- for reading from a binary stream (has methods like
ReadInt32)
System.IO.Memor yStream -- you will create one of these out of your byte
array and read it with the BinaryReader

I would suggest these classes as it is relatively easy to understand and I
think it fits what you want to do the best.

-OR-

If those don't suit you then try these:

System.BitConve rter -- for converting byte arrays to individual primatives
and back.
System.Buffer -- for copying arrays of one primative to arrays of another
primative.
System.Text.Enc oding -- for converting byte arrays of various encodings to
Unicode strings and back.

(I would suggest this mode if you find the stream doesn't perform well,
although it should be good enough)
You could use BitConverter to convert to an int, which you would then cast
to your enum. Then you'd do the same for the next 4-bytes. If you had any
long series of values (like several ints in a row) that needed to be
converted to an array, use the Buffer class. If you need to read a string,
use the Encoding class.

-OR-

Last, and least:

unsafe pointers

(and I don't recommend this unless you're either insane or really worried
about performance)
You can use C#'s "unsafe" context to do things the way you would in C/C++
and access the memory directly with pointers.
(Footnote: If you are dealing with endian-specifc values and plan on ever
running your code on other platforms [e.g. Mono on MacOSX] you MAY want to
keep endian-ness in mind.)

--Matthew W. Jackson

"Pete Davis" <pd******@hotma il.com> wrote in message
news:96******** *************** *******@news.me ganetnews.com.. .
I've never done this in C# so I don't know what the appropriate way of doing it is.

I've got an array of bytes and I need to convert the array into "usable"
data. For example, the first 4 bytes need to be converted to an enum. The
next 4 bytes to a 32-bit int. And so on. I'm basically populating a struct
with the data. How does one do this in C#?

Thanks.

Pete

--
http://www.petedavis.net

Nov 15 '05 #3
Mathew,
Wow, thanks for the myriad of options. That's about the most complete
answer I've ever gotten on a programming newsgroup. Fortunately, I think the
MemoryStream will be sufficient for my needs. I'm not going to worry about
performance for the moment, but it's nice to knwo I have options.

Pete
--
http://www.petedavis.net

"Matthew W. Jackson" <th************ ********@NOSPAM .NOSPAM> wrote in message
news:ut******** ******@TK2MSFTN GP09.phx.gbl...
There are several approaches you can take:

Take a look at these .NET Framework classes:

System.IO.Binar yReader -- for reading from a binary stream (has methods like ReadInt32)
System.IO.Memor yStream -- you will create one of these out of your byte
array and read it with the BinaryReader

I would suggest these classes as it is relatively easy to understand and I
think it fits what you want to do the best.

-OR-

If those don't suit you then try these:

System.BitConve rter -- for converting byte arrays to individual primatives
and back.
System.Buffer -- for copying arrays of one primative to arrays of another
primative.
System.Text.Enc oding -- for converting byte arrays of various encodings to
Unicode strings and back.

(I would suggest this mode if you find the stream doesn't perform well,
although it should be good enough)
You could use BitConverter to convert to an int, which you would then cast
to your enum. Then you'd do the same for the next 4-bytes. If you had any long series of values (like several ints in a row) that needed to be
converted to an array, use the Buffer class. If you need to read a string, use the Encoding class.

-OR-

Last, and least:

unsafe pointers

(and I don't recommend this unless you're either insane or really worried
about performance)
You can use C#'s "unsafe" context to do things the way you would in C/C++
and access the memory directly with pointers.
(Footnote: If you are dealing with endian-specifc values and plan on ever
running your code on other platforms [e.g. Mono on MacOSX] you MAY want to
keep endian-ness in mind.)

--Matthew W. Jackson

"Pete Davis" <pd******@hotma il.com> wrote in message
news:96******** *************** *******@news.me ganetnews.com.. .
I've never done this in C# so I don't know what the appropriate way of

doing
it is.

I've got an array of bytes and I need to convert the array into "usable"
data. For example, the first 4 bytes need to be converted to an enum. The next 4 bytes to a 32-bit int. And so on. I'm basically populating a struct with the data. How does one do this in C#?

Thanks.

Pete

--
http://www.petedavis.net


Nov 15 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
13924
by: matt melton | last post by:
Hi there, I am trying to write a method that accepts an array of any primitive type and will return the same array without copying memory as an array of bytes. ie. I'd like to be able to do something like: char chars = "Hello!"; byte bytes = (byte) chars;
4
10309
by: Hal Vaughan | last post by:
If I have a byte and I convert it to string (String sData = new String(byte bData), then convert it back (byte bData = sData.getBytes()), will all data be intact, or do Strings have problems with bytes that are not printable characters? I've tested this and it seems to work fine, but I want to make sure there isn't some condition or situation I'm not aware of that could cause problems. I'm doing this because it's easier to do some of my...
2
2679
by: Govind | last post by:
Hi All, I want to Convert 32 bit integers to byte in right alighed format . For 32 = the usual way is BitConverter.GetBytes(int32)==> xx xx 00 00 , but i want right aligned like 00 00 xx xx.Is there any way. Regards, Govind.
4
16467
by: Joseph Suprenant | last post by:
I have an array of unsigned chars and i would like them converted to an array of ints. What is the best way to do this? Using RedHat 7.3 on an Intel Pentium 4 machine. Having trouble here, hope someone can help Thanks
1
12520
by: Darrel | last post by:
I am using binary writer to write an array of bytes to disk. However, my data starts out as an array of sbytes. I am currently type casting each array element in a for loop. Is there a faster method for converting an array of sbytes to an array of bytes? Thanks, Darrel
1
2154
by: UKuser | last post by:
Hi Guys, I have a program which converts Excel spreadsheets to Javascript and allows interactivity. However it can't convert it to PHP, which is obviously better for users to view (in case J/S is turned off). How would I go about converting some of this created code (example JS below), or is there an easier way to get PHP to do the calculations itself? I am aware of an excel-server product but this is too expensive and doesnt actually...
4
3194
by: gg9h0st | last post by:
i'm a newbie studying php. i was into array part on tutorial and it says i'll get an array having keys that from member variable's name by converting an object to array. i guessed "i can get public members but not protected, private, static members"
9
30518
by: Gregory.A.Book | last post by:
I am interested in converting sets of 4 bytes to floats in C++. I have a library that reads image data and returns the data as an array of unsigned chars. The image data is stored as 4-byte floats. How can I convert the sets of 4 bytes to floats? Thanks, Greg Book
0
2031
by: anide | last post by:
Hi all I’ve some problem, I’m trying to converting a sorting algorithm from C++ to C#. In C++ I’ve compiled it using MSVC and its working properly, and in C# I’m using .NET Framework 2.0 (Visual Studio 2005). The problem occurred when I trying to opening and reading file: ============= C++ ============= void LoadSourceFile(char * fileName, unsigned char * data, int length)
0
8968
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9473
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9334
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9259
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6750
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4569
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4824
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.