What is the easiest way to convert primitives to a byte array? I tried the
BinaryFormatter serialization but it serializes objects so when I serialized
an and int it took 54 bytes instead of 4. I tried something like the
following but it won't compile (I admit I use generics a lot but haven't
written many so this may be way off):
class X<T>
{
public byte[] ToByteArray(T val)
{
BinaryWriter bw = new BinaryWriter(ne w MemoryStream()) ;
bw.Write(val);
BinaryReader br = new BinaryReader(bw .BaseStream);
br.BaseStream.P osition = 0;
return br.ReadBytes((i nt)br.BaseStrea m.Length);
}
}
I don't want to have an overloaded method for every primitive type. Is there
an easy way to do this...or have the overloads already been written to do
this and I am just missing it? It seems like a pretty basic task that should
be there somewhere already.
thanks 10 3389
Well, there might be a better way tucked away - but how about (a little
grubby, but it seems to work...):
Marc
using System;
using System.Reflecti on;
static class Program
{
static void Main()
{
byte[] data = BitHelper<int>. Write(12345);
int value = BitHelper<int>. Read(data, 0);
}
static class BitHelper<T>
{
static BitHelper()
{
MethodInfo method =
typeof(BitConve rter).GetMethod ("GetBytes", new Type[] { typeof(T) });
if (method == null) throw new NotSupportedExc eption();
write = (Func<T,
byte[]>)Delegate.Crea teDelegate(type of(Func<T, byte[]>), method);
method = typeof(BitConve rter).GetMethod ("To" +
typeof(T).Name, new Type[] {typeof(byte[]), typeof(int)});
if (method == null) throw new NotSupportedExc eption();
read = (Func<byte[], int,
T>)Delegate.Cre ateDelegate(typ eof(Func<byte[], int, T>), method);
}
static Func<byte[], int, Tread;
static Func<T, byte[]write;
public static T Read(byte[] buffer, int index) { return
read(buffer, index); }
public static byte[] Write(T value) { return write(value); }
public static int Write(T value, byte[] buffer, int index)
{
byte[] tmp = Write(value);
tmp.CopyTo(buff er, index);
return tmp.Length;
}
}
}}
Oh; if you are using .NET 2.0/3.0, then you'll need to add:
delegate TArg3 Func<TArg1, TArg2, TArg3>(TArg1 arg1, TArg2 arg2);
delegate TArg2 Func<TArg1, TArg2>(TArg1 arg1);
Marc
Of course you can probably do some more interesting things using unsafe
code...
Marc
Marc,
Actually that's a pretty impressive solution. I thought about using
reflection to do it (although I must admit it would have taken me a while to
figure out how to do what you gave me)
However...this is going to be done millions/billions of times for this
application and I want to avoid the overhead of using reflection to
accomplish the task. If it comes to that I will overload the primitives like
they do with the system.convert( ) routines etc...
"Marc Gravell" wrote:
Well, there might be a better way tucked away - but how about (a little
grubby, but it seems to work...):
Marc
using System;
using System.Reflecti on;
static class Program
{
static void Main()
{
byte[] data = BitHelper<int>. Write(12345);
int value = BitHelper<int>. Read(data, 0);
}
static class BitHelper<T>
{
static BitHelper()
{
MethodInfo method =
typeof(BitConve rter).GetMethod ("GetBytes", new Type[] { typeof(T) });
if (method == null) throw new NotSupportedExc eption();
write = (Func<T,
byte[]>)Delegate.Crea teDelegate(type of(Func<T, byte[]>), method);
method = typeof(BitConve rter).GetMethod ("To" +
typeof(T).Name, new Type[] {typeof(byte[]), typeof(int)});
if (method == null) throw new NotSupportedExc eption();
read = (Func<byte[], int,
T>)Delegate.Cre ateDelegate(typ eof(Func<byte[], int, T>), method);
}
static Func<byte[], int, Tread;
static Func<T, byte[]write;
public static T Read(byte[] buffer, int index) { return
read(buffer, index); }
public static byte[] Write(T value) { return write(value); }
public static int Write(T value, byte[] buffer, int index)
{
byte[] tmp = Write(value);
tmp.CopyTo(buff er, index);
return tmp.Length;
}
}
}}
I am sure I am missing sothing but can you use:
BitConverter.Ge tBytes()?
Rene.
On May 20, 9:21*am, Brian <Br...@discussi ons.microsoft.c omwrote:
What is the easiest way to convert primitives to a byte array? I tried the
BinaryFormatter serialization but it serializes objects so when I serialized
an and int it took 54 bytes instead of 4. I tried something like the
following but it won't compile (I admit I use generics a lot but haven't
written many so this may be way off):
* * class X<T>
* * {
* * * * public byte[] ToByteArray(T val)
* * * * {
* * * * * * BinaryWriter bw = new BinaryWriter(ne w MemoryStream()) ;
* * * * * * bw.Write(val);
* * * * * * BinaryReader br = new BinaryReader(bw .BaseStream);
* * * * * * br.BaseStream.P osition = 0;
* * * * * * return br.ReadBytes((i nt)br.BaseStrea m.Length);
* * * * }
* * }
I don't want to have an overloaded method for every primitive type. Is there
an easy way to do this...or have the overloads already been written to do
this and I am just missing it? It seems like a pretty basic task that should
be there somewhere already.
thanks
Brian wrote:
Actually that's a pretty impressive solution. I thought about using
reflection to do it (although I must admit it would have taken me a while to
figure out how to do what you gave me)
However...this is going to be done millions/billions of times for this
application and I want to avoid the overhead of using reflection to
accomplish the task.
Marc's solution only uses reflection once per instantiation of the
generic type. The reflected methods are stored in delegates, so you pay
approximately the cost of a virtual method dispatch per read and write,
not the cost of a reflection call.
-- Barry
-- http://barrkel.blogspot.com/
Ok, never mind, I am such a bonehead!!!
But trust me, one of this day I am bound to post a smart response…. I
can feel it :)
On May 20, 11:17*am, qglyirnyf...@ma ilinator.com wrote:
I am sure I am missing sothing but can you use:
BitConverter.Ge tBytes()?
Rene.
On May 20, 9:21*am, Brian <Br...@discussi ons.microsoft.c omwrote:
What is the easiest way to convert primitives to a byte array? I tried the
BinaryFormatter serialization but it serializes objects so when I serialized
an and int it took 54 bytes instead of 4. I tried something like the
following but it won't compile (I admit I use generics a lot but haven't
written many so this may be way off):
* * class X<T>
* * {
* * * * public byte[] ToByteArray(T val)
* * * * {
* * * * * * BinaryWriter bw = new BinaryWriter(ne w MemoryStream()) ;
* * * * * * bw.Write(val);
* * * * * * BinaryReader br = new BinaryReader(bw .BaseStream);
* * * * * * br.BaseStream.P osition = 0;
* * * * * * return br.ReadBytes((i nt)br.BaseStrea m.Length);
* * * * }
* * }
I don't want to have an overloaded method for every primitive type. Is there
an easy way to do this...or have the overloads already been written to do
this and I am just missing it? It seems like a pretty basic task that should
be there somewhere already.
thanks- Hide quoted text -
- Show quoted text -
If it comes to that I will overload the primitives like
they do with the system.convert( ) routines etc...
If overloading is an option, then just use BitConverter directly. I
only used generics here because it was in the original subject; this
has the dubious advantage that you can use it deep within generic
code, when you don't know the type of T, so overloads (such as
BitConverter) can't be used directly.
Re the performance, the whole setup is cached; all you have is a pre-
checked delegate invoke, so it shouldn't be too bad - not /quite/ as
quick as direct calls to an overload, but not far behind.
Re the performance...
and it might have been even better had I remembered to mark the
delegates as readonly! It should say:
static readonly Func<byte[], int, Tread;
static readonly Func<T, byte[]write;
That way the CLR knows it won't change, and /may/ be better-able to
optimise it. Or if nothing else, it prevents us from changing the
value accidentally ;-p
Marc This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Fred |
last post by:
Are primitives objects?
int i = 3;
System.out.println(i.getClass());
doesn't compile. Get an error message
"int can't be dereferenced"
But yet the docs for class Object say:
Class Object is the root of the class hierarchy. Every class has Object as
|
by: Andreas Huber |
last post by:
What follows is a discussion of my experience with .NET generics & the
..NET framework (as implemented in the Visual Studio 2005 Beta 1),
which leads to questions as to why certain things are the way they
are.
***** Summary & Questions *****
In a nutshell, the current .NET generics & .NET framework make it
sometimes difficult or even impossible to write truly generic code.
For example, it seems to be impossible to write a truly generic
|
by: Benton |
last post by:
Hi there,
I could serialize a class until I added this member to it:
private Dictionary<string><TableMapper> = new
Dictionary<string><TableMapper>();
The class has the attribute, but now it won't serialize.
Does any one know of a code sample that shows how can this be done? Any
|
by: Testguy |
last post by:
Hi,
I have been reading various messages in this group, and could not find
an answer regarding what I am trying to do. At least, I could not find
an easy answer.
I am trying to figure out how to read and XML file and put the data in
fields in a VB application, and also how to write the information to
an XML file (either to a new file or modifying an existing file.
|
by: greg.merideth |
last post by:
Is it possible to serialize SortedList<T,V> or do I need to come up
with my own method to get the data into and out the list? I'm pretty
sure I know that it's "no" I'm just curious if there are any tricks
around.
Here's the error I get when I attempt to serialize a SortedList<T,V>
Unhandled Exception: System.NotSupportedException: The type
System.Collections.S
ortedList is not supported because it implements IDictionary.
| |
by: Michael |
last post by:
I have a problem with serialization in my project. Serialization is working
fine so far but when I increase the version of the application in the
AssemblyInfo.cs I get an exception. So I created a test project and found out
that the problems is related to generic lists. When I serialize a List<T>
with version 1.0.0.0 of the application and deserialize it with version
1.0.0.1 of the application I get an exception stating:
Could not load...
|
by: Joe |
last post by:
Hi
I have a Generics List in a PropertyGrid
I am able to Serialize it to XML but when I try to deserialize back to the
class of the PropertyGrid
The Constructor doesn't seem to fire to reload the saved settings
Can anyone see something that I have missed ?
|
by: ThunderMusic |
last post by:
Hi,
We need to serialize (binary) objects containing generic collections. The
thing is, when we try to get the objects back (deserialize) with a different
instance of the application, we receive an exception stating the constructor
of the generic class does not exist. So Is there a way to obtain the
resulting classes of the generics we use so we can add them as "normal" code
in our app? We can develop our own starting from non-generic...
|
by: raylopez99 |
last post by:
KeyDown won't work KeyPress fails KeyDown not seen
inspired by a poster here:http://tinyurl.com/62d97l I found some
interesting stuff, which I reproduce below for newbies like me.
The main reason you would want to do this is for example to trigger
something from an OnPaint event without resorting to boolean switches--
say if a user presses the "M" key while the program is Painting, the
user gets the PaintHandler to do something else. ...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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...
| |
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,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |