473,655 Members | 3,105 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics and casting questions

Hello all,

First of all, sorry for multiple question per one thread. I have two
questions. First what I think might be the easier problem. I am
capturing data from an embedded device which I need to display data.
One particular piece of data is a 32 bit floating point value. The
problem I am having is converting the 4-byte value which is read via
an RS-232 link. How can I cast the 4-byte value to a value type float
correctly? I have tried placing shifting the bytes into either a int
or UInt32 (which is a class from what I understand) then casting that
value as a float, but it doesn't work correctly. This operation looks
similar to
int value = (int)((byteCode[0] << 24 ) |
(byteCode[1] << 16 ) |
(byteCode[2] << 8 ) |
(byteCode[3] ));

float valueF = (float)value;

This obviosuly doesn't appear to work correctly. The embedded device
stores the 32-bit float in the standard IEEE format from my current
understanding which should be compatable with the MS compiler. So how
would I get this conversion to work correctly?
The second question I have deals with using Generics. I have an
interface which looks like
interface IScriptVar<Twhe re T : struct
{
string ToString();
string ToHexString( );
void SetValue( T value, UInt32 index );
void SetValue( T[] values, int index );
T GetValue( int index );
....
}

public class CScriptVar<T: IScriptVar<Twhe re T : struct
{
... Implemented Interface methods and members
}

which I have also created a List for them

public class CScriptVarStrin gList<CScriptVa rString:
IList<CScriptVa rString>
{
....
}

Then in my code I have the following

private CScriptVarList< CScriptVar<byte > ScriptVarsBytes ;
private CScriptVarList< CScriptVar<shor t> ScriptVarsShort ;
private CScriptVarList< CScriptVar<int> ScriptVarsInts;
private CScriptVarList< CScriptVar<floa t> ScriptVarsFloat ;

I have a method when passed in certain arguments it will return on the
of the objects. Since they all implement several interfaces I would
like to return the object and then cast it to the generic/general type
of IScriptVar<T>, but this does not work correctly. I have something
like the following currently, but I don't think it is right since I am
forced to qualify using a (struct or data types) byte, short, int or
float.

((IScriptVar<in t>)scriptVar).T oHexString();

or

((CScriptVar<in t>)scriptVar).T oHexString();
I was hoping to use a generic form, but perhaps this is not possible.
When I retrieve the object I could perform a typeof conditional then
switch between each one of the System.Type (struct or data types)
which would look like

if ( scriptVar.GetTy pe() == typeof(IScriptV ar<byte>))
{ ((CScriptVar<by te>)scriptVar). ToHexString(); }

if ( scriptVar.GetTy pe() == typeof(IScriptV ar<short>))
{ ((CScriptVar<sh ort>)scriptVar) .ToHexString(); }

if ( scriptVar.GetTy pe() == typeof(IScriptV ar<int>))
{ ((CScriptVar<in t>)scriptVar).T oHexString(); }

if ( scriptVar.GetTy pe() == typeof(IScriptV ar<float>))
{ ((CScriptVar<fl oat>)scriptVar) .ToHexString(); }

Does anyone know of a elegant way of handling this or perhaps a better
approach.

Mark

Jul 18 '06 #1
3 1739
"LongBow" <pi***@mud.pool a écrit dans le message de news:
qa************* *************** ****@4ax.com...

| Does anyone know of a elegant way of handling this or perhaps a better
| approach.

I would separate out the non-generic methods of the interface to a
non-generic base interface and then derive the generic interface from that :

interface IScriptVar
{
string ToString();
string ToHexString( );
}

interface IScriptVar<T: IScriptVar where T : struct
{
void SetValue( T value, UInt32 index );
void SetValue( T[] values, int index );
T GetValue( int index );
....
}

Then you can treat all instances the same as IScriptVar, allowing you to
access the ToString and ToHexString methods without having to know the exact
type.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Jul 18 '06 #2
LongBow wrote:
First what I think might be the easier problem. I am
capturing data from an embedded device which I need to display data.
One particular piece of data is a 32 bit floating point value. The
problem I am having is converting the 4-byte value which is read via
an RS-232 link. How can I cast the 4-byte value to a value type float
correctly? I have tried placing shifting the bytes into either a int
or UInt32 (which is a class from what I understand) then casting that
value as a float, but it doesn't work correctly. This operation looks
similar to
int value = (int)((byteCode[0] << 24 ) |
(byteCode[1] << 16 ) |
(byteCode[2] << 8 ) |
(byteCode[3] ));

float valueF = (float)value;
This is at too high a level - this looks at the *number* in the int and
just makes valueF have the same *numerical* value. You want to be
working at the bit level.
>
This obviosuly doesn't appear to work correctly. The embedded device
stores the 32-bit float in the standard IEEE format from my current
understanding which should be compatable with the MS compiler. So how
would I get this conversion to work correctly?
Use BitConverter.To Single on the byte array.
--
Larry Lard
la*******@googl email.com
The address is real, but unread - please reply to the group
For VB and C# questions - tell us which version
Jul 18 '06 #3
Larry Lard wrote:
LongBow wrote:
First what I think might be the easier problem. I am
capturing data from an embedded device which I need to display data.
One particular piece of data is a 32 bit floating point value. The
problem I am having is converting the 4-byte value which is read via
an RS-232 link. How can I cast the 4-byte value to a value type float
correctly? I have tried placing shifting the bytes into either a int
or UInt32 (which is a class from what I understand) then casting that
value as a float, but it doesn't work correctly. This operation looks
similar to
int value = (int)((byteCode[0] << 24 ) |
(byteCode[1] << 16 ) |
(byteCode[2] << 8 ) |
(byteCode[3] ));

float valueF = (float)value;

This is at too high a level - this looks at the *number* in the int and
just makes valueF have the same *numerical* value. You want to be
working at the bit level.

This obviosuly doesn't appear to work correctly. The embedded device
stores the 32-bit float in the standard IEEE format from my current
understanding which should be compatable with the MS compiler. So how
would I get this conversion to work correctly?

Use BitConverter.To Single on the byte array.
I had an additional question, why isn't type T allowed for the
BitConverter class? The Convert class allows type T to be used. Is
there a specific reason why? I have also noticed that bit wise
operations are not allowed for type T operation also. Why is the case?
I figure since the width of the data type is not known until run-time
so the bit wise operation doesn't know which opcode to use during
compile time.

Yes, thanks for both individuals who have replied as it has helped
greatly. I am still having problems the generics as bit-wise operations
are not allowed and I can't use the BitConverter class for some of the
operation I want.

Mark
>

--
Larry Lard
la*******@googl email.com
The address is real, but unread - please reply to the group
For VB and C# questions - tell us which version
Jul 18 '06 #4

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

Similar topics

13
1772
by: Anders Borum | last post by:
Hello! Now that generics are introduces with the next version of C#, I was wondering what kind of performance gains we're going to see, when switching from e.g. the general hashtable to a hashtable that supports (or implements) generics? I haven't tried generics hands-on, but I would assume that once you don't have to do casting anymore, things could speed up quite a bit.
4
25405
by: KC | last post by:
Could some one explain to me the casting rules for sending generic lists, ex. List<Person>, to a function that accepts List<object>? I cannot get the following easy-cheesy app to work. I get the following error: Argument '1': cannot convert from 'GenericsPOC.ArticleCollection' to 'System.Collections.Generic.IList<object>' I tried casting specifically to IList<object> but then I get a runtime error: Unable to cast object of type...
23
2538
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics vs C++ templates. Does anyone knows a workaround to do this ? Thx : public class C<T> { private T myValue;
4
2566
by: krahenbuhl | last post by:
Dear All, I've a question related to Generics and casting in c# 2.0. I've a class called Client which implements interface IClient. I'd like to do: LinkedList<Client> clients; public LinkedList<IClient> getClients() { return clients;
5
2916
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have an "AppleBasket" which is a class that contains a collection of apples. So, some code: class Fruit{ }
7
2201
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
3
1805
by: psyCK0 | last post by:
Hi all! I have a problem of casting generics to their base type. In the code below I first define a BaseList class that can hold items of any type that inherits from BaseItem. I then define a DerivedList that can hold items of the type DerivedItem, which inherits from BaseList. So far so good... But if I somehow get an object that I know is a subclass of BaseList (and therefor holds subclasses of BaseItem) and try to cast it to...
10
1611
by: Frank Rizzo | last post by:
Given the inneficiencies of ArrayList and Hashtable on 64-bit systems, I am converting them to List<and Dictionary<respectively. It's a pretty massive system, so there are a lot of casts. For instance. ArrayList aaa = new ArrayList(); aaa.Add(new Customer()); aaa.Add(new Customer()); aaa.Add(new Customer()); Customer c = (Customer) aaa;
8
1468
by: Tony Johansson | last post by:
Hello! I have read that in practice, casting proved to be several times faster than using a generic. So the main reason to use generics is not that the performance is better because that's not the case. The only reason is that it's type-safe. I must ask if anyone has made any significant performance improvement using
0
8380
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
8816
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
8710
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
8497
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
5627
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();...
0
4150
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
4299
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2721
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
2
1598
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.