473,387 Members | 1,520 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Safe union?

Hi group,

I wonder - can anybody tell me if it is safe to make a union like this:

union Event {
unsigned char charData[4];

struct {
unsigned int channel : 4;
unsigned int type : 4;
unsigned int note : 8;
int velocity : 8;
} fields;
};

- "safe" in the way that it is guaranteed that:
* fields.channel will return the 4 MSB of charData[0]
* fields.type will return the 4 LSB of charData[0]
* fields.note will return charData[1]
* fields.velocity will return charData[2]

Obviously, if I allocate the struct myself the compiler will guarantee that
no problems arise regarding alignment etc.

But what if the char data I am to interpret comes from "the framework" and I
have no idea where it is allocated? Imagine a function like this
(implementing a virtual framework function):

void interpretCharData(char *data) {
// will this give me problems?
Event *evt = (Event *)data;

// start using the bit fields of the struct here
}

And how about portability? I'm thinking alignment, endiannes, [insert
portability issue I do not know about yet here]

Thanks in advance!

Best regards,
Mogens
Aug 14 '05 #1
5 1560
Mogens Heller Jensen wrote:
Hi group,

I wonder - can anybody tell me if it is safe to make a union like this:

union Event {
unsigned char charData[4];

struct {
unsigned int channel : 4;
unsigned int type : 4;
unsigned int note : 8;
int velocity : 8;
} fields;
};

- "safe" in the way that it is guaranteed that:
* fields.channel will return the 4 MSB of charData[0]
* fields.type will return the 4 LSB of charData[0]
* fields.note will return charData[1]
* fields.velocity will return charData[2]
It is most certainly not guarenteed. This is implementation defined.
It may be this way on your particular platform, it may not.

Obviously, if I allocate the struct myself the compiler will guarantee that
no problems arise regarding alignment etc.

But what if the char data I am to interpret comes from "the framework" and I
have no idea where it is allocated? Imagine a function like this
(implementing a virtual framework function):

void interpretCharData(char *data) {
// will this give me problems?
Event *evt = (Event *)data;

// start using the bit fields of the struct here
}

And how about portability? I'm thinking alignment, endiannes, [insert
portability issue I do not know about yet here]


While there may still be implementation defined issues, this struct
might be more portable (I know of no compiler that would not do what you
specified).

#include <iostream>

class Event
{
unsigned char channel_n_type;

public:
unsigned char note;

signed char velocity;

unsigned channel()
{
return channel_n_type & 0xf;
}

unsigned channel( unsigned i_val )
{
channel_n_type = ( 0xf0 & channel_n_type ) | ( i_val & 0xf );
return i_val & 0xf;
}

unsigned type()
{
return ( channel_n_type & 0xf0 ) >> 4;
}

unsigned type( unsigned i_val )
{
channel_n_type = (0xf & channel_n_type) | (( i_val & 0xf )<<4);
return i_val & 0xf;
}
};

int main()
{
char x[3];

Event * e = reinterpret_cast<Event *>( x );

e->channel(2);
e->type(3);
e->note = 4;
e->velocity = 5;

std::cout << e->channel() << "\n";
std::cout << e->type() << "\n";
std::cout << int( e->note ) << "\n";
std::cout << int( e->velocity ) << "\n";

}

Aug 14 '05 #2

"Gianni Mariani" <gi*******@mariani.ws> wrote in message
news:s-********************@speakeasy.net...
Mogens Heller Jensen wrote:
Hi group,

I wonder - can anybody tell me if it is safe to make a union like this:

union Event {
unsigned char charData[4];

struct {
unsigned int channel : 4;
unsigned int type : 4;
unsigned int note : 8;
int velocity : 8;
} fields;
};

- "safe" in the way that it is guaranteed that:
* fields.channel will return the 4 MSB of charData[0]
* fields.type will return the 4 LSB of charData[0]
* fields.note will return charData[1]
* fields.velocity will return charData[2]


It is most certainly not guarenteed. This is implementation defined. It
may be this way on your particular platform, it may not.

Obviously, if I allocate the struct myself the compiler will guarantee
that no problems arise regarding alignment etc.

But what if the char data I am to interpret comes from "the framework"
and I have no idea where it is allocated? Imagine a function like this
(implementing a virtual framework function):

void interpretCharData(char *data) {
// will this give me problems?
Event *evt = (Event *)data;

// start using the bit fields of the struct here
}

And how about portability? I'm thinking alignment, endiannes, [insert
portability issue I do not know about yet here]


While there may still be implementation defined issues, this struct might
be more portable (I know of no compiler that would not do what you
specified).

#include <iostream>

class Event
{
unsigned char channel_n_type;

public:
unsigned char note;

signed char velocity;

unsigned channel()
{
return channel_n_type & 0xf;
}

unsigned channel( unsigned i_val )
{
channel_n_type = ( 0xf0 & channel_n_type ) | ( i_val & 0xf );
return i_val & 0xf;
}

unsigned type()
{
return ( channel_n_type & 0xf0 ) >> 4;
}

unsigned type( unsigned i_val )
{
channel_n_type = (0xf & channel_n_type) | (( i_val & 0xf )<<4);
return i_val & 0xf;
}
};

int main()
{
char x[3];

Event * e = reinterpret_cast<Event *>( x );

e->channel(2);
e->type(3);
e->note = 4;
e->velocity = 5;

std::cout << e->channel() << "\n";
std::cout << e->type() << "\n";
std::cout << int( e->note ) << "\n";
std::cout << int( e->velocity ) << "\n";

}


Thank you for the quick reply!

And thanks for the nice class example. I think I will go for something like
it :o)

But what is the difference between using reinterpret_cast<...> and just
doing the cast? I googled it up and read about it on MSDN, but it seems that
it is just as unsafe as the usual explicit casting.

The best,
Mogens
Aug 14 '05 #3
Mogens Heller Jensen wrote:
But what is the difference between using reinterpret_cast<...> and just
doing the cast? I googled it up and read about it on MSDN, but it seems that it is just as unsafe as the usual explicit casting.


but its easier to find than C-style cast
Aug 14 '05 #4
Mogens Heller Jensen wrote:
....

But what is the difference between using reinterpret_cast<...> and just
doing the cast? I googled it up and read about it on MSDN, but it seems that
it is just as unsafe as the usual explicit casting.


C style cast, i.e. "(T) x" is actually different. It overloads many
things, it also is capable of doing things that are not possible using
the C++ style casts. (C style casts can access a private base class, C++
style casts cannot.).

I use the C++ style casts now just because it's more explicit.
reinterpret casts are usually bad and so if I see alot of code that has
reinterpret casts all over it, then I will probably be looking at it
more carefully. In fact, I try to keep all my reinterpret casts in one
"type safety" class and never use reinterpret casts anywhere else.

In your case, I would probably create a "reader class" like this.

struct EventReaderWriter
{
...
Feed( const char * x ) ...

const Event * Get()
{
x += sizeof( Event );
if ( x > end ?? etc ) ...
return reinterpt_cast<const Event *>( x );
}

Event * Push()
{
...
return reinterpt_cast<Event *>( y );
}
};

It would probably look very different to this, but I think you'll get
the idea.
Aug 14 '05 #5

"Gianni Mariani" <gi*******@mariani.ws> wrote in message
news:-K********************@speakeasy.net...
Mogens Heller Jensen wrote:
...

But what is the difference between using reinterpret_cast<...> and just
doing the cast? I googled it up and read about it on MSDN, but it seems
that it is just as unsafe as the usual explicit casting.


C style cast, i.e. "(T) x" is actually different. It overloads many
things, it also is capable of doing things that are not possible using the
C++ style casts. (C style casts can access a private base class, C++ style
casts cannot.).

I use the C++ style casts now just because it's more explicit. reinterpret
casts are usually bad and so if I see alot of code that has reinterpret
casts all over it, then I will probably be looking at it more carefully.
In fact, I try to keep all my reinterpret casts in one "type safety" class
and never use reinterpret casts anywhere else.

In your case, I would probably create a "reader class" like this.

struct EventReaderWriter
{
...
Feed( const char * x ) ...

const Event * Get()
{
x += sizeof( Event );
if ( x > end ?? etc ) ...
return reinterpt_cast<const Event *>( x );
}

Event * Push()
{
...
return reinterpt_cast<Event *>( y );
}
};

It would probably look very different to this, but I think you'll get the
idea.


I get the idea :o)

Thanks for the input!

-Mogens
Aug 14 '05 #6

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

Similar topics

18
by: srijit | last post by:
Hello, I would like to know the definition of type safe and whether Python can be considered as a type safe language. Similarly are Java, C# or C++ type safe? Regards, Srijit
1
by: SW | last post by:
Hello, Can anyone show me how to define in an XSD schema that an element in an XML document can either contain no text, or if it does contain text that the text has to be of a specific type. ...
1
by: Timothy Madden | last post by:
I want to stoare in a queue values of type LPCTSTR, int, long, BYTE, WORD, DWORD and many enum types. Can I write such a queue in a type safe maner (idealy no casts involved) ? Thank you...
5
by: Simon Elliott | last post by:
I'd like to do something along these lines: struct foo { int i1_; int i2_; }; struct bar {
36
by: Robert Vazan | last post by:
I am looking for other people's attempts to create safe subset of C and enforce it with scripts. Does anybody know about anything like this? By "safe", I mean the following: * Strongly typed...
4
by: dingoatemydonut | last post by:
The quoted text below is from comp.std.c which originated from a discussion on comp.lang.c. I've edited out the parts that do not apply to my question. Robert Gamble wrote: > Dann Corbit wrote:...
4
by: arak123 | last post by:
consider the following oversimplified and fictional code public void CreateInvoices(Invoice invoices) { IDbCommand command=Util.CreateDbCommand(); foreach(Invoice invoice in invoices) //lets...
18
by: digz | last post by:
Hi , I am trying to write a class that encapsulates a Union within it , I intend the code to be exception safe. can someone please review it and tell me if I have done the right thing , are...
9
by: jason.cipriani | last post by:
All right, I'm in this weird situation that's hard to explain but I've put together a small example program that represents it. Please bear with the fact that some of the stuff in the example seems...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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...

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.