Suppose I have a structure
Private Structure MyStruct
Dim el1 As Byte
Dim el2 As Int16
Dim el3 As Byte
End Structure
I want to convert this into a byte array where
Dim st as MyStruct
Dim arr(3) As Byte
arr(0) = st.el1
arr(1) = st.el2 >> 8
arr(2) = st.el2 And &HFF
arr(3) = st.el3
Is there a neat way to do this in the NET Framework? Ideally, it would be
generic, so that it doesn't have to be hand coded for each different
structure that I have. It would also be nice to be able to specify big or
little endian, in the case of el2.
Thanks
Charles 9 12639
I'm not sure if it's what you're after, but have a look at the
StructLayoutAttribute and FieldOffsetAttribute classes that let you define
the memory positions of each member of the structure:
E.g.
---------------
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)> Public Structure MyColor
<FieldOffset(0)> Public Red As Byte
<FieldOffset(1)> Public Green As Byte
<FieldOffset(2)> Public Blue As Byte
<FieldOffset(3)> Public Alpha as Byte
<FieldOffset(0)> Public ColorValue As Integer
End Structure
---------------
In, the above example the layout of the structure is such that ColorValue is
made up of the same 4 bytes that the Red, Green, Blue and alpha color bytes
use.
I know this ain't exactly converting it to an array, but it's the closest I
can think of without resorting to serializing the structure.
Hope this is a little help,
Trev.
"Charles Law" <bl***@nowhere.com> wrote in message
news:un**************@TK2MSFTNGP09.phx.gbl... Suppose I have a structure
Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure
I want to convert this into a byte array where
Dim st as MyStruct Dim arr(3) As Byte
arr(0) = st.el1 arr(1) = st.el2 >> 8 arr(2) = st.el2 And &HFF arr(3) = st.el3
Is there a neat way to do this in the NET Framework? Ideally, it would be generic, so that it doesn't have to be hand coded for each different structure that I have. It would also be nice to be able to specify big or little endian, in the case of el2.
Thanks
Charles
Almost forgot, but you could use Reflection to get the values of the fields
and add them to the array.
e.g.
---------------------------
Dim objTest As MyTest ' Structure containing 3 byte fields
Dim aFields As FieldInfo() = GetType(MyTest).GetFields
Dim aValues As New ArrayList
'Populate the structure
objTest.Val1 = 1
objTest.Val2 = 2
objTest.Val3 = 3
' Get the byte values of each field
For Each objField As FieldInfo In aFields
If objField.FieldType.Equals(GetType(Byte)) Then
' Add the byte
aValues.Add(cbyte(objField.GetValue(objTest)))
Else
' Code to determine how many bytes I should add
' (i.e. check the datatype of the field and use little or big-endian
' math to get the byte values
' ......
End If
Next
' Convert the arraylist to an array of bytes
Dim aBytes As Byte() = DirectCast(aValues.ToArray(GetType(Byte)), Byte())
---------------------------
I'm not sure that it would return the fields in the same order all the time
though, but it should be generic enough as long as you handle situations
where the structure contains fields that are not bytes (integers, strings,
floats, objects etc.)
HTH,
Trev
Hi Trev
I had noticed the StructLayoutAttribute class and thought it might be a step
in the right direction, but I am not sure how to make the last step.
Serialization sounds like code, which I may have to resort to if there isn't
a class already designed to do this type of conversion.
I will have a play with the FieldOffsetAttribute class.
Cheers
Charles
"Trev Hunter" <hu*********@hotmail.com> wrote in message
news:eJ**************@TK2MSFTNGP11.phx.gbl... I'm not sure if it's what you're after, but have a look at the StructLayoutAttribute and FieldOffsetAttribute classes that let you define the memory positions of each member of the structure:
E.g.
---------------
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)> Public Structure MyColor <FieldOffset(0)> Public Red As Byte <FieldOffset(1)> Public Green As Byte <FieldOffset(2)> Public Blue As Byte <FieldOffset(3)> Public Alpha as Byte <FieldOffset(0)> Public ColorValue As Integer End Structure
---------------
In, the above example the layout of the structure is such that ColorValue
is made up of the same 4 bytes that the Red, Green, Blue and alpha color
bytes use.
I know this ain't exactly converting it to an array, but it's the closest
I can think of without resorting to serializing the structure.
Hope this is a little help,
Trev. "Charles Law" <bl***@nowhere.com> wrote in message news:un**************@TK2MSFTNGP09.phx.gbl... Suppose I have a structure
Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure
I want to convert this into a byte array where
Dim st as MyStruct Dim arr(3) As Byte
arr(0) = st.el1 arr(1) = st.el2 >> 8 arr(2) = st.el2 And &HFF arr(3) = st.el3
Is there a neat way to do this in the NET Framework? Ideally, it would
be generic, so that it doesn't have to be hand coded for each different structure that I have. It would also be nice to be able to specify big
or little endian, in the case of el2.
Thanks
Charles
Thanks Trev.
I will have a try with this. If I wrap it all up in a class then, as you
say, it will be generic enough.
Cheers
Charles
"Trev Hunter" <hu*********@hotmail.com> wrote in message
news:e8**************@TK2MSFTNGP11.phx.gbl... Almost forgot, but you could use Reflection to get the values of the
fields and add them to the array.
e.g.
---------------------------
Dim objTest As MyTest ' Structure containing 3 byte fields Dim aFields As FieldInfo() = GetType(MyTest).GetFields Dim aValues As New ArrayList
'Populate the structure objTest.Val1 = 1 objTest.Val2 = 2 objTest.Val3 = 3
' Get the byte values of each field For Each objField As FieldInfo In aFields
If objField.FieldType.Equals(GetType(Byte)) Then
' Add the byte aValues.Add(cbyte(objField.GetValue(objTest)))
Else ' Code to determine how many bytes I should add ' (i.e. check the datatype of the field and use little or
big-endian ' math to get the byte values ' ...... End If
Next
' Convert the arraylist to an array of bytes Dim aBytes As Byte() = DirectCast(aValues.ToArray(GetType(Byte)), Byte())
---------------------------
I'm not sure that it would return the fields in the same order all the
time though, but it should be generic enough as long as you handle situations where the structure contains fields that are not bytes (integers, strings, floats, objects etc.)
HTH,
Trev
> Serialization sounds like code, which I may have to resort to if there isn't a class already designed to do this type of conversion.
With serialization, you can convert any class or structure that is marked
with the <Serializable> attribute into a stream of bytes (and to an array of
bytes) for saving to a disk or remoting accross a network. If you're only
interested in the bytes used by the fields, use the reflection method
mentioned in another post as serialization will add headers and could
transform the data so it can be stored in different ways (e.g. XML or
Binary) etc.
HTH,
Trev.
"Charles Law" <bl***@nowhere.com> wrote in message
news:e$**************@TK2MSFTNGP09.phx.gbl... Hi Trev
I had noticed the StructLayoutAttribute class and thought it might be a
step in the right direction, but I am not sure how to make the last step. Serialization sounds like code, which I may have to resort to if there
isn't a class already designed to do this type of conversion.
I will have a play with the FieldOffsetAttribute class.
Cheers
Charles
"Trev Hunter" <hu*********@hotmail.com> wrote in message news:eJ**************@TK2MSFTNGP11.phx.gbl... I'm not sure if it's what you're after, but have a look at the StructLayoutAttribute and FieldOffsetAttribute classes that let you
define the memory positions of each member of the structure:
E.g.
---------------
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)> Public Structure MyColor <FieldOffset(0)> Public Red As Byte <FieldOffset(1)> Public Green As Byte <FieldOffset(2)> Public Blue As Byte <FieldOffset(3)> Public Alpha as Byte <FieldOffset(0)> Public ColorValue As Integer End Structure
---------------
In, the above example the layout of the structure is such that
ColorValue is made up of the same 4 bytes that the Red, Green, Blue and alpha color bytes use.
I know this ain't exactly converting it to an array, but it's the
closest I can think of without resorting to serializing the structure.
Hope this is a little help,
Trev. "Charles Law" <bl***@nowhere.com> wrote in message news:un**************@TK2MSFTNGP09.phx.gbl... Suppose I have a structure
Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure
I want to convert this into a byte array where
Dim st as MyStruct Dim arr(3) As Byte
arr(0) = st.el1 arr(1) = st.el2 >> 8 arr(2) = st.el2 And &HFF arr(3) = st.el3
Is there a neat way to do this in the NET Framework? Ideally, it would be generic, so that it doesn't have to be hand coded for each different structure that I have. It would also be nice to be able to specify big or little endian, in the case of el2.
Thanks
Charles
Ah. I am only interested in the bytes, exactly as they appear in the
structure, so I will stick with reflection.
Charles
"Trev Hunter" <hu*********@hotmail.com> wrote in message
news:em**************@tk2msftngp13.phx.gbl... Serialization sounds like code, which I may have to resort to if there isn't a class already designed to do this type of conversion. With serialization, you can convert any class or structure that is marked with the <Serializable> attribute into a stream of bytes (and to an array
of bytes) for saving to a disk or remoting accross a network. If you're only interested in the bytes used by the fields, use the reflection method mentioned in another post as serialization will add headers and could transform the data so it can be stored in different ways (e.g. XML or Binary) etc.
HTH,
Trev.
"Charles Law" <bl***@nowhere.com> wrote in message news:e$**************@TK2MSFTNGP09.phx.gbl... Hi Trev
I had noticed the StructLayoutAttribute class and thought it might be a step in the right direction, but I am not sure how to make the last step. Serialization sounds like code, which I may have to resort to if there isn't a class already designed to do this type of conversion.
I will have a play with the FieldOffsetAttribute class.
Cheers
Charles
"Trev Hunter" <hu*********@hotmail.com> wrote in message news:eJ**************@TK2MSFTNGP11.phx.gbl... I'm not sure if it's what you're after, but have a look at the StructLayoutAttribute and FieldOffsetAttribute classes that let you define the memory positions of each member of the structure:
E.g.
---------------
Imports System.Runtime.InteropServices
<StructLayout(LayoutKind.Explicit)> Public Structure MyColor <FieldOffset(0)> Public Red As Byte <FieldOffset(1)> Public Green As Byte <FieldOffset(2)> Public Blue As Byte <FieldOffset(3)> Public Alpha as Byte <FieldOffset(0)> Public ColorValue As Integer End Structure
---------------
In, the above example the layout of the structure is such that ColorValue is made up of the same 4 bytes that the Red, Green, Blue and alpha color bytes use.
I know this ain't exactly converting it to an array, but it's the closest I can think of without resorting to serializing the structure.
Hope this is a little help,
Trev. "Charles Law" <bl***@nowhere.com> wrote in message news:un**************@TK2MSFTNGP09.phx.gbl... > Suppose I have a structure > > Private Structure MyStruct > Dim el1 As Byte > Dim el2 As Int16 > Dim el3 As Byte > End Structure > > I want to convert this into a byte array where > > Dim st as MyStruct > Dim arr(3) As Byte > > arr(0) = st.el1 > arr(1) = st.el2 >> 8 > arr(2) = st.el2 And &HFF > arr(3) = st.el3 > > Is there a neat way to do this in the NET Framework? Ideally, it
would be > generic, so that it doesn't have to be hand coded for each different > structure that I have. It would also be nice to be able to specify
big or > little endian, in the case of el2. > > Thanks > > Charles > >
Hi Mattias
Well spotted. I have converted it and tried it succesfully. It is certainly
shorter and quicker than the reflection route, but perhaps less flexible.
The latter makes it possible to code for big endian and little endian,
whereas the former simply does a byte for byte copy.
I will keep both up my sleeve I think.
For completeness, I have included both solutions below.
<reflection>
Imports System.Reflection
Public Class Struct
Public Shared Function Convert(ByVal MyStruct As Object) As Byte()
Dim al As ArrayList
Dim Fields As FieldInfo() = MyStruct.GetType.GetFields
al = New ArrayList
For Each fld As FieldInfo In Fields
If fld.FieldType.Equals(GetType(Byte)) Then
' Add byte to array list
al.Add(CByte(fld.GetValue(MyStruct)))
ElseIf fld.FieldType.Equals(GetType(Int16)) Then
' Add 16-bit value to array list
Dim i16 As Int16
i16 = CType(fld.GetValue(MyStruct), Int16)
al.Add(CByte(i16 >> 8))
al.Add(CByte(i16 And &HFF))
Else
Throw New Exception("Cannot convert type.")
End If
Next fld
Return DirectCast(al.ToArray(GetType(Byte)), Byte())
End Function
End Class
</reflection>
<memcopy>
Public Function RawSerialize(ByVal anything As Object) As Byte()
Dim rawsize As Integer = Marshal.SizeOf(anything)
Dim buffer As IntPtr = Marshal.AllocHGlobal(rawsize)
Marshal.StructureToPtr(anything, buffer, False)
Dim rawdatas(rawsize - 1) As Byte
Marshal.Copy(buffer, rawdatas, 0, rawsize)
Marshal.FreeHGlobal(buffer)
Return rawdatas
End Function
Public Function RawDeserialize(ByVal rawdatas As Byte(), ByVal anytype As
Type) As Object
Dim rawsize As Integer = Marshal.SizeOf(anytype)
If (rawsize > rawdatas.Length) Then
Return Nothing
End If
Dim buffer As IntPtr = Marshal.AllocHGlobal(rawsize)
Marshal.Copy(rawdatas, 0, buffer, rawsize)
Dim retobj As Object = Marshal.PtrToStructure(buffer, anytype)
Marshal.FreeHGlobal(buffer)
Return retobj
End Function
</memcopy>
Cheers
Charles
"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:uj**************@TK2MSFTNGP09.phx.gbl... Charles,
Check out
http://groups.google.com/groups?selm...%40tkmsftngp05
It's C# code, but shouldn't be too hard to translate to VB. Mattias
-- Mattias Sjögren [MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup.
Charles,
In addition to the other suggestions, I would consider reflection using
System.IO.BinaryReader & BinaryWriter (where the BinaryReader & BinaryWriter
are operating on a MemoryStream, as the MemoryStream is the array of
Bytes!). However this may be slightly more work then the ArrayList
Especially if the structure contained reference types that
Marshal.StructureToPtr & PtrToStructure did not know how to handle
correctly...
However I suspect Mattias's suggestion will be the most useful in most
cases.
Hope this helps
Jay
"Charles Law" <bl***@nowhere.com> wrote in message
news:un**************@TK2MSFTNGP09.phx.gbl... Suppose I have a structure
Private Structure MyStruct Dim el1 As Byte Dim el2 As Int16 Dim el3 As Byte End Structure
I want to convert this into a byte array where
Dim st as MyStruct Dim arr(3) As Byte
arr(0) = st.el1 arr(1) = st.el2 >> 8 arr(2) = st.el2 And &HFF arr(3) = st.el3
Is there a neat way to do this in the NET Framework? Ideally, it would be generic, so that it doesn't have to be hand coded for each different structure that I have. It would also be nice to be able to specify big or little endian, in the case of el2.
Thanks
Charles
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Prabhu |
last post by:
Hi,
I have to send a structure through TCPClient socket. we can send only
byte array through the socket,
So please any one can help me by telling How to convert a struct object into
an byte...
|
by: Joe Thompson |
last post by:
Hi
I am new to C# and am rewritting some C++ code. I want to send a byte array over a serial port. The elements of the byte array are really a structure I have populated. My question is, how do...
|
by: Mel WEaver |
last post by:
Hello,
I have the following delphi structure for a binary file. I'm looking
for idea how to read this file.
Mel
type
TMenuDataStruct = packed record
exename : string;
|
by: Ken Dopierala Jr. |
last post by:
Hi,
I'm reading the header file of a PCX image and I need to convert 2 bytes
to a short. How would I go about doing this? I know that they are bytes 8
& 9 in my byte array. I'm not sure how to...
|
by: Charles Law |
last post by:
I thought this was going to be straight forward, given the wealth of
conversion functions in .NET, but it is proving more convoluted than
imagined.
Given the following
<code>
Dim ba(1) As...
|
by: Dennis |
last post by:
If I have a structure like;
Public Structure myStructureDef
Public b() as Byte
Public t as String
End Structure
If I pass this structure, will the values in the array b be stored on the...
|
by: moni |
last post by:
Hey,
My buffer contains a short int, some char, and a structure in form of
a byte array.
Read the string as:
TextBox4.Text = System.Text.Encoding.ASCII.GetString(buffer1, 0, 31);
Read...
|
by: Paul Jarvis |
last post by:
I have a large structure, below is a simplistic version of my structure:
public struct MeanMinMaxSd
{
public double mean;
public double min;
public double max;
public double sd;
}
|
by: =?Utf-8?B?QXlrdXQgRXJnaW4=?= |
last post by:
Hi Willy,
Thank you very much for your work.
C++ code doesnot make any serialization.
So at runtime C# code gives an serialization error at
"msg_file_s sa = (msg_file_s) bf.Deserialize(ms);"...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: Vimpel783 |
last post by:
Hello!
Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: PapaRatzi |
last post by:
Hello,
I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
| |