468,549 Members | 1,955 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,549 developers. It's quick & easy.

Convert Structure to Byte Array

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
Nov 20 '05 #1
9 12127
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

Nov 20 '05 #2
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
Nov 20 '05 #3
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


Nov 20 '05 #4
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

Nov 20 '05 #5
> 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



Nov 20 '05 #6
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
>
>



Nov 20 '05 #7
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.
Nov 20 '05 #8
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.

Nov 20 '05 #9
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

Nov 20 '05 #10

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Joe Thompson | last post: by
2 posts views Thread by Mel WEaver | last post: by
8 posts views Thread by Ken Dopierala Jr. | last post: by
14 posts views Thread by Dennis | last post: by
1 post views Thread by Paul Jarvis | last post: by
5 posts views Thread by =?Utf-8?B?QXlrdXQgRXJnaW4=?= | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.