473,769 Members | 1,917 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trouble casting a struct with bit fields

Surely this is a no-brainer, but sometimes I think I must have no
brain (no comments, please<g>). Anyway, I have the following struct
containing bit fields:

struct ExtPenStyle
{
unsigned long style : 4;
unsigned long : 4; // unused
unsigned long endcap : 2;
unsigned long : 2; // unused
unsigned long join : 2;
unsigned long : 2; // unused
unsigned long type : 1;
unsigned long : 15; // unused
};

I tried casting from/to unsigned long using static_cast,
reinterpret_cas t and C-style cast. The compiler refuses to do it, but
I need to call API code which expects an unsigned long with bitmapped
values.

I know I could use a union or memcpy(), but I wonder if there is a
cleaner way? Thanks.

#include <iostream>
#include <ostream>

// struct ExtPenStyle
// { see above };

int main()
{
using std::cout;
using std::endl;

ExtPenStyle xps = ExtPenStyle();
unsigned long ulong(static_ca st<unsigned long>(xps));// no good?!?
cout << "Sizeof ExtPenStyle: " << sizeof(ExtPenSt yle) << endl;
return 0;
}

--
Bob Hairgrove
No**********@Ho me.com
Jul 22 '05 #1
3 4614
Sam
ExtPenStyle xps = ExtPenStyle();
unsigned long ulong(static_ca st<unsigned long>(xps));// no good?!? Try this:
unsigned long ulong(*reinterp ret_cast<unsign ed long*>(&xps));
cout << "Sizeof ExtPenStyle: " << sizeof(ExtPenSt yle) << endl;
return 0;
}

--
Bob Hairgrove
No**********@Ho me.com

Jul 22 '05 #2
On Wed, 17 Nov 2004 10:55:40 -0000, "Sam" <ma*******@hotm ail.com>
wrote:
Try this:
unsigned long ulong(*reinterp ret_cast<unsign ed long*>(&xps));


Yes, this seems to work. However, I think I will use a union -- it
certainly saves a lot of typing, and seems more intuitive.

Thank you!
--
Bob Hairgrove
No**********@Ho me.com
Jul 22 '05 #3
Bob Hairgrove <in*****@bigfoo t.com> wrote in message news:<oi******* *************** **********@4ax. com>...
Surely this is a no-brainer, but sometimes I think I must have no
brain (no comments, please<g>). Anyway, I have the following struct
containing bit fields:

struct ExtPenStyle
{
unsigned long style : 4;
unsigned long : 4; // unused
unsigned long endcap : 2;
unsigned long : 2; // unused
unsigned long join : 2;
unsigned long : 2; // unused
unsigned long type : 1;
unsigned long : 15; // unused
};

I tried casting from/to unsigned long using static_cast,
reinterpret_cas t and C-style cast. The compiler refuses to do it, but
I need to call API code which expects an unsigned long with bitmapped
values.


The compile is right, and the API couldn't care whether you
actually used bitfiels.

E.g.

template< int pos, int length >
struct field {
static unsigned long mask = (1UL<<length-1);
long get( unsigned long src ) { return (src>>pos) & mask }
void set( unsigned long& dest, long val ) {
val &= mask;
dest &= ~(mask<<pos);
dest |= val << pos;
}
};
struct ExtPenStyle
{
unsigned long bits;

field<0, 4> style_pos;
unsigned long get_style_pos() { return style_pos.get(b its); }
void set_style_pos(u nsigned long v) { style_pos.set(b its, v); }

//etcetera
};

No casts needed. The compiler will do pretty much the same,
but this is more reliable (there are at least two ways to stuff
bitfields in a long, MSB or LSB first. Here YOU choose.)

HTH,
Michiel Salters
Jul 22 '05 #4

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

Similar topics

4
3480
by: Jacob Jensen | last post by:
This question has probably been asked a million time, but here it comes again. I want to learn the difference between the three type cast operators: static_cast, reinterpret_cast, dynamic_cast. A good way to do this is by example. So I will give an example and please tell me what you think: I have a base class A with a virtual destructor, and a class B that is it inherits publicly from A and defines som extra stuff.
12
2216
by: Ney André de Mello Zunino | last post by:
Hello. I have been having some trouble dealing with bit fields. The following is a simple program that demonstrates it. #include <iomanip> #include <iostream> struct instrucao_i {
3
7047
by: Rob Jackson | last post by:
HiI've got a struct, known by file A.c, which contains a pointer to struct B. Struct B is unknown by file A.c (it is declared in C.h), and contains a typedef enum, which is declared in a file B.h, which is included in file A.c (this is getting really confusing, I know!).I want to access the enum in file A.c, but don't want to include file C.h, for various reasons.I've tried casting the enum, but still get the error "Dereferencing pointer...
8
5135
by: Servé Lau | last post by:
Consider the following code: struct X { float f; }; struct Y { struct X x; }; void func(struct X *x) {} int main(void) { struct Y y; func(&y);
17
2572
by: goldfita | last post by:
I saw some code that appeared to do something similar to this struct foo { char offset; int d; }; struct foo { int a; int b;
6
2524
by: crook | last post by:
I have code below and it works properly but when I'm compiling it with "--pedantic" flag, GCC(3.4.2) shows such warning: "ISO C forbids casting nonscalar to the same type". How can I change this code to get rid of this warning? /*parameters is void* type*/ struct params p = ( struct params )*( ( struct params * )parameters );
2
2641
by: pallav | last post by:
I'm using an old sparse matrix C library in my C++ code and I'd like to know how to downcast a boost::shared_ptr to char *. The sparse matrix data structure is like this: struct sm_element_struct { /* other fields here */ ....... char *user_word; /* user-defined word */ };
4
15310
by: Schkhan | last post by:
Hi, I am sturggling with a peace of code mainly its about casting a pointer to one type of structure to a pointer to another type of structure. the confusion begins with the following line...(modified to highlight the actual prob) #define TEST_MACRO(first) ((struct second *) &first) /*here it would return a pointer to second, but the question is why it uses Here in this example "first" and "second" are two different structures*/
4
3043
by: Wally Barnes | last post by:
Can someone help a poor C++ programmer that learned the language before there was a standard lib .. etc ? Basically I have two classes that look something like below: template <class T> class ListLogic { public: struct LogicBase {
0
9420
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,...
0
10205
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
10035
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...
0
8863
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7401
isladogs
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...
0
6662
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
5441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3556
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2811
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.