473,748 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

assigning bit-field structure

/* With the following: */
typedef struct
{
unsigned char a : 1;
unsigned char b : 1;
} sss_t;
sss_t sss;
unsigned char ppp;

main()
{
sss = (sss_t)ppp; /* why 'invalid cast expression'? */

sss = *(sss_t*)&ppp; /* why OK? */
}

/*
Used Sun compiler.

Thanks,

Kees
*/

Nov 14 '05 #1
13 11491


- Kees van der Bent - wrote:
/* With the following: */
typedef struct
{
unsigned char a : 1;
unsigned char b : 1;
} sss_t;
sss_t sss;
unsigned char ppp;

main()
{
sss = (sss_t)ppp; /* why 'invalid cast expression'? */
You are trying to convert an unsigned char to an user-defined data
type, that are noway related , as far as the compiler is concerned.

sss = *(sss_t*)&ppp; /* why OK? */


&ppp changes it to UCHAR * , and then you are converting to (sss_t
*) [ it really gets dangerous here, but you are allowed to do it, since
they are addresses after all ] .
Having converted it, you are dereferencing it back. I am assuming you
are writing this for learning purposes only. But as such , such cast
expressions ( changing pointers of a given type to a diff. type ) ought
not to be used in any serious project ;) .

HTH .
Nov 14 '05 #2
"- Kees van der Bent -" <kv*@mbalance.m oc> wrote in message
news:40******** *************@n ews.xs4all.nl.. .
/* With the following: */
typedef struct
{
unsigned char a : 1;
unsigned char b : 1;
} sss_t;
sss_t sss;
unsigned char ppp;
Why are these global?
main()
{
sss = (sss_t)ppp; /* why 'invalid cast expression'? */
You're not gonna like it, but you can't do it, because... you can't do it!
You cannot cast between a scalar and an aggregate type. Think of it this
way: an aggregate (such as a structure) is an object containing more than
one value (even if the structure contains only one field, we are talking in
general terms here). A scalar only contains one value. How would you convert
from one to another? What sense would it make?
sss = *(sss_t*)&ppp; /* why OK? */
Conversions between pointers are allowed. Whether the result of such
conversion is meaningful, or even a valid pointer, is quite another
question.
}

/*
Used Sun compiler.
Doesn't matter.
Thanks,

Kees
*/


Peter
Nov 14 '05 #3
Rakesh <dr************ ******@yahoo.co m> spoke thus:
&ppp changes it to UCHAR * , and then you are converting to (sss_t

^^^^^
ITYM "unsigned char". UCHAR is not a C keyword, although of course
you can typedef it yourself if you're so inclined.

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #4
- Kees van der Bent - wrote:
/* With the following: */
typedef struct
{
unsigned char a : 1;
unsigned char b : 1;
unsigned char is not a valid type for a bit field.
} sss_t;
sss_t sss;
unsigned char ppp;

main()
{
sss = (sss_t)ppp; /* why 'invalid cast expression'? */
ppp is a scalar; the type sss_t isn't.
sss = *(sss_t*)&ppp; /* why OK? */
Because C lets you do all sorts of silly things using pointers.
}

Nov 14 '05 #5
Oh yeah :) of course , i meant unsigned char . I was a bit too lazy to
type in that. Thanks for pointing it out, though.

Christopher Benson-Manica wrote:
Rakesh <dr************ ******@yahoo.co m> spoke thus:

&ppp changes it to UCHAR * , and then you are converting to (sss_t


^^^^^
ITYM "unsigned char". UCHAR is not a C keyword, although of course
you can typedef it yourself if you're so inclined.


--

--
Rakesh Kumar
** Remove nospamplz from my email address for my real email **
Nov 14 '05 #6
Martin Ambuhl <ma*****@earthl ink.net> wrote in message news:<c6******* *****@ID-227552.news.uni-berlin.de>...
- Kees van der Bent - wrote:
/* With the following: */
typedef struct
{
unsigned char a : 1;
unsigned char b : 1;
unsigned char is not a valid type for a bit field.


Yes I read this in K&R and wondered why the compiler did not
warn at all. What do you think?
} sss_t;

Nov 14 '05 #7
"Peter Pichler" <pi*****@pobox. sk> wrote in message news:<40******* *@mk-nntp-2.news.uk.tisca li.com>...
"- Kees van der Bent -" <kv*@mbalance.m oc> wrote in message
news:40******** *************@n ews.xs4all.nl.. .
/* With the following: */
typedef struct
{
unsigned char a : 1;
unsigned char b : 1;
} sss_t;
sss_t sss;
unsigned char ppp;
Why are these global?


I quickly typed in a small piece of code that gave the
same results as my real code. I don't like globals either.
main()
{
sss = (sss_t)ppp; /* why 'invalid cast expression'? */
You're not gonna like it, but you can't do it, because... you can't do it!
You cannot cast between a scalar and an aggregate type. Think of it this
way: an aggregate (such as a structure) is an object containing more than
one value (even if the structure contains only one field, we are talking in
general terms here). A scalar only contains one value. How would you convert
from one to another? What sense would it make?


I like to view a bit-field structure as a special case of of scalar:
a regular scalar with the added convenience of being able to 'address'
certain bits. Isn't this how bit-fields are used in hardware device
drivers (mapping certain registers)?

In my case my input data is of type unsigned char which needs to be
mapped/assigned on/to a bit-field structure. Instead of writing out
all the nuts al bolts (with ... >> 4 & 0x3 ...) I want C to help me
out here and let the compiler do the work for me.
sss = *(sss_t*)&ppp; /* why OK? */
Conversions between pointers are allowed. Whether the result of such
conversion is meaningful, or even a valid pointer, is quite another
question.


I agree with you. But this seems to be the only way to get the result
I want. Although I'm confident that this will work in practice, the
question remains if this works according to the C standard. How is bit-
field structure allignment specified in the C spec?
}

/*
Used Sun compiler.


Doesn't matter.
Thanks,

Kees
*/


Peter

Nov 14 '05 #8
- Kees van der Bent - wrote:
Martin Ambuhl <ma*****@earthl ink.net> wrote in message news:<c6******* *****@ID-227552.news.uni-berlin.de>...
- Kees van der Bent - wrote:
/* With the following: */
typedef struct
{
unsigned char a : 1;
unsigned char b : 1;


unsigned char is not a valid type for a bit field.

Yes I read this in K&R and wondered why the compiler did not
warn at all. What do you think?


That you either don't have the diagnostic level set properly or that you
are not invoking your compiler in conforming mode.
Nov 14 '05 #9
In article <news:f5******* *************** **@posting.goog le.com>
- Kees van der Bent - <kv*****@mail.c om> writes:
I like to view a bit-field structure as a special case of of scalar:
a regular scalar with the added convenience of being able to 'address'
certain bits. Isn't this how bit-fields are used in hardware device
drivers (mapping certain registers)?
Some people write code like that. Others write code that survives
changing compilers. :-)
In my case my input data is of type unsigned char which needs to be
mapped/assigned on/to a bit-field structure. Instead of writing out
all the nuts al bolts (with ... >> 4 & 0x3 ...) I want C to help me
out here and let the compiler do the work for me.
Unfortunately, as Dennis Ritchie himself once put it, C's bitfields
are "a botch and a blemish". For instance:
How is bit-field structure allignment specified in the C spec?


It is not.

Much worse, however, is the fact that two different compilers FOR THE
SAME MACHINE may reverse the order of the bits in some bitfield:

/* device connected to motorola 68010; C compiler has 16-bit int */
struct hardware_reg {
unsigned int go:1; /* set to 1 to make device run */
unsigned int cmd:3; /* command */
unsigned int ctl:4; /* control bits */
unsigned int dma:1; /* set to 1 to use DMA */
unsigned int :3; /* unused */
unsigned int status:4; /* device status */
unsigned int addr; /* DMA address */
};

Compiled with Compiler A, the "go" bit is (as desired) the high bit
of the first 16-bit word, but compiled with Compiler B, the "go" bit
becomes the *low* bit of that word.

Using "unsigned short csr, addr;" and defining bits for the control
and status register works on every compiler you will find for that
68010-based system (even those with 32-bit ints). C gives you (the
programmer) no control whatsoever of where the bits in the bitfield
wind up. If you want to write this sort of code, you might consider
Ada, which has the necessary construct (the "representa tion clause").
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #10

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

Similar topics

22
465
by: ajay | last post by:
Why would a new of object be created without assigning it to any of variable? new A; ??? tx
4
2245
by: jonas.email | last post by:
Im am doing a major project and after a long time debugging i found this rather funny (=annoying) bug. In its simple form, this is the main problem: int main(void) { float f1 = 0.3f; float f2 = 0.1f; printf("%f, %.10f, %f, %.10f\n", f1, f1, f2, f2); if(f1 == 3*f2)
6
10155
by: adamrfrench | last post by:
Let it be mentioned that Javascript is not my forte, so the solution to this could very well be a simple one. I am working on an AJAX function where I can pass a URL and the target ID in, and have the function update the target ID with the URL. There is a bit more to it then that, but that is the basics. my difficulty comes when I try to assign a variable to: "document.getElementById('-> var gose here <-').innerHTML"
12
3942
by: bollod | last post by:
Is there any benefit to declaring a variable: x = (1<<12); instead of: x = 4096; (besides the geek appeal of course ;-) )
10
5745
by: Linny | last post by:
Hi All, I am pasting a piece of code which executes fine on 32 bit system but fails with a segmentation fault when compiled 64 bit compiler.I am using a HP-UX C compiler on PA-RISC system. This code was picked up from a document mentioning portability issues from 32 to 64 bit systems. But when I include the system file <malloc.h, the code executes fine on both the systems.
27
2442
by: csledge | last post by:
Hi, I am trying to compute a 64 bit result from 2 32 bit registers, How do I get the carry into the higher word ? Also is %lld correct ? #include<stdio.h> long long int64( long x, int y); main() { printf("%lld \n",int64(0xffffffff,1));
4
4190
by: Felix Kater | last post by:
Hi, when I use something like int Shift= 3; long Value= 1 << Shift; What is the data type of the const value '1' here? In other terms: What is the possible maximum of 'Shift' here?
43
17223
by: emyl | last post by:
Hi all, here's an elementary question. Assume I have declared two variables, char *a, **b; I can then give a value to a like a="hello world";
1
1527
by: The Pythonista | last post by:
I've been wondering for a while about whether assigning to __class__ is bad form or not. Specifically, I mean doing so when some other method of implementing the functionality you're after is available (i.e. using an adapter, or something like the strategy pattern). To give an example and a non-example of what I'm talking about, consider the following recipes from the online Python Cookbook: Ring Buffer:...
9
16058
by: shortyzms | last post by:
I'm having a problem with assigning 64-bit hex values to unsigned long variables in MS VS2005 c++ compiler. unsigned long Number; Number = 0x1000000000000000UL; After this declaration and assignment, the value in Number is always 0. However, if the hex value is 0x0000000000000001, then the value is 1 as expected. It seems like the compiler is truncating the most significant 32 bits. How can I make this work?
0
8996
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
8832
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
9562
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
9386
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
9333
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
9254
tracyyun
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...
0
6078
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
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3319
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

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.