473,795 Members | 2,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

bitfield & union strange ?!



hi all

i put in this email source code so u can copy and paste to verify strange

first : in this example bit size is a BYTE ?!
second : in the last printf output is wrong ?

?

best regards all
#include <stdio.h>
int main ( void )
{
struct snibble
{
unsigned a : 1 ;
unsigned b : 1 ;
unsigned c : 1 ;
unsigned d : 1 ;
} ;

struct sbyte
{
struct snibble high ;
struct snibble low ;
} ;
union ubyte
{
struct sbyte a ;
char c ;
} ;

struct snibble n ;
struct sbyte sb ;
union ubyte ub ;

printf ("\n %u " , sizeof ( ub ) ) ;
printf ("\n %u " , sizeof ( sb ) ) ;
printf ("\n %u " , sizeof ( n ) ) ;
printf ("\n %u " , sizeof ( char ) ) ;

ub.c = 'a' ;

printf ("\n\n %c " , ub.c ) ;
printf ("\n %u " , ub.a.high ) ;
printf ("\n %u " , ub.a.low ) ;

}

Jul 22 '05 #1
2 2156
On Sun, 01 Aug 2004 20:14:02 GMT, Claudio <da************ @libero.it>
wrote in comp.lang.c++:


hi all

i put in this email source code so u can copy and paste to verify strange

first : in this example bit size is a BYTE ?!
second : in the last printf output is wrong ?
What are you talking about? Do you think that the output of the
program after you compiled it with your compiler is WRONG? How can we
tell, you did not show the output on your system when you ran the
program.

Here is the output I got when I built and ran the program with one
particular compiler:

========
8
8
4
1

a
97
0
========
best regards all
#include <stdio.h>
int main ( void )
{
struct snibble
{
unsigned a : 1 ;
unsigned b : 1 ;
unsigned c : 1 ;
unsigned d : 1 ;
} ;
The size of an 'snibble' struct must be at least one byte, but it may
be larger. Many implementations allocate bit-field structures in int
size units, so it may well be sizeof(int).
struct sbyte
{
struct snibble high ;
struct snibble low ;
} ;
The size of an 'sbyte' struct must be at least two bytes, but it may
be larger. It must be at least two times the size of a 'snibble'
structure.
union ubyte
{
struct sbyte a ;
char c ;
} ;

struct snibble n ;
struct sbyte sb ;
union ubyte ub ;

printf ("\n %u " , sizeof ( ub ) ) ;
printf ("\n %u " , sizeof ( sb ) ) ;
printf ("\n %u " , sizeof ( n ) ) ;
printf ("\n %u " , sizeof ( char ) ) ;

ub.c = 'a' ;

printf ("\n\n %c " , ub.c ) ;
printf ("\n %u " , ub.a.high ) ;
printf ("\n %u " , ub.a.low ) ;
}


What is the output of the program when you ran it, and what do you
think is wrong with it?

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #2
> first : in this example bit size is a BYTE ?!
no, bit size is always a bit. but you defined:
struct nibble
{
unsigned a:1;
...
};
in this case _unsigned_ evaluates on most platforms nowadays (since they are
32-bit architectures) to _unsigned_ _int_ (i.e. to 32 bit, or _four_ byte)!
you have to declare your struct like this:
struct nibble
{
unsigned char a:1;
unsigned char b:1;
unsigned char c:1;
unsigned char d:1;
};

since, the compiler always have to put your struct in at least one byte, you
also want to declare which bits you want of this byte.
so the better way is (a..highest bit, d..lowest bit):
rem.: bits a used from lowest first to highest!

struct highnibble
{
unsigned char unused:4;
unsigned char d:1;
unsigned char c:1;
unsigned char b:1;
unsigned char a:1;
};

struct lownibble
{
unsigned char d:1;
unsigned char c:1;
unsigned char b:1;
unsigned char a:1;
unsigned char unused:4;
};

union ubyte
{
struct highnibble a;
struct lownibble b;
char c;
}

than
printf ("\n %u " , sizeof (struct highnibble) ) ;
printf ("\n %u " , sizeof (srtuct lownibble) ) ;
printf ("\n %u " , sizeof ( char ) ) ;
should all evalute to one!
in your last use of ubyte
union ubyte ub.c = 'a' ;

printf ("\n\n %c " , ub.c ) ;
printf ("\n %u " , ub.a.high ) ;
printf ("\n %u " , ub.a.low ) ;

you have made the mistake, that the nibble will always access the structure
- or in your case a 32-bit integer - and not simply four bits. if you want
to print out a nibble you have to either use a bit-mask, or use c++ and
operator overload.
but if you take your structure as used, you will never only access a nibble
(part) of your byte!

example (c-code):
#include <stdio.h>

#define ACCESS_NIBBLE_L OW(_x) ((_x)&0x0f)
#define ACCESS_NIBBLE_H IGH(_x) (((_x)&0xf0)>>4 )
int main(void)
{
const unsigned char N_HIGH=0xf0, N_LOW=0x0f;
typedef struct
{
unsigned char x:4; /* bits 0..3 */
unsigned char d:1; /* bit 4 .. 2^4=16 */
unsigned char c:1; /* bit 5 .. 2^5=32 */
unsigned char b:1; /* bit 6 .. 2^6=64 */
unsigned char a:1; /* bit 8 .. 2^7=128*/
} nibblehigh;

typedef struct
{
unsigned char d:1; /* bit 0 .. 2^0=1 */
unsigned char c:1; /* bit 1 .. 2^1=2 */
unsigned char b:1; /* bit 2 .. 2^2=4 */
unsigned char a:1; /* bit 3 .. 2^3=16*/
unsigned char y:4; /* bits 4..7 */
} nibblelow;

typedef union
{
nibblehigh high;
nibblelow low;
char c;
} ubyte;

printf("\n %u", sizeof(nibblehi gh));
printf("\n %u", sizeof(nibblelo w));
printf("\n %u", sizeof(ubyte));
printf("\n %u", sizeof(char));

ubyte ub;
ub.c = 65+32; /* 'a' */

printf("\n\n %u %c %c", ub.c, ub.high, ub.low);
printf("\n %u %u", ACCESS_NIBBLE_H IGH(ub.c), ACCESS_NIBBLE_L OW(ub.c));

ub.high.c = 0; /* make uppercase (remove bit 5 : 32=2^5) */

printf("\n\n %u %c %c", ub.c, ub.high, ub.low);
printf("\n %u %u", ACCESS_NIBBLE_H IGH(ub.c), ACCESS_NIBBLE_L OW(ub.c));

return 0;
}

hope it will help
godfired
Jul 22 '05 #3

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

Similar topics

14
1865
by: CJM | last post by:
I have a query which produces different results in the Access query builder and in an ASP page (via ADO) An example of the query is: ---------------------------------------------------------- Select 'Ranked' as Source, H.HotelName, H.TelNo, H.URL, H.Location, H.HotelID, Rank from (Hotels H Inner Join PrefHotels P on H.HotelID = P.HotelID) Inner Join Locations L on P.LocID = L.LocID where Rank is not null and Rank > 0 and L.LocID=2
0
2144
by: Neculai Macarie | last post by:
Hi! Using Union and Order By gives strange behaviour in the following test-case: drop table if exists gallery; drop table if exists gallery_categ; # create test tables create table gallery (d_image_small char(100), d_image_big char(100)); create table gallery_categ (d_image char(100)); # insert test data
2
10752
by: Gerry | last post by:
I am relatively new to DB2 and having a problem with a simple union statement. Running Db2UDB version 8.1.1 on Aix 5.1 The union and union all SQL statements I am running produce the same results. No duplicates are being eliminated in the union. To verify, I ran SQL with union statements against system tables.
9
5255
by: Davide Bruzzone | last post by:
Greetings all... I need to create a number of bitfield structs whose contents are smaller than the size of an int. For example: typedef struct foo FOO; struct foo { unsigned char fieldOne: 2, fieldTwo: 6; };
4
10472
by: Ray | last post by:
When a single-bit bitfield that was formed from an enum is promoted/cast into an integer, does ANSI C say anything about whether that integer should be signed or unsigned? SGI IRIX cc thinks it is an unsigned integer, so I see a +1 if the bit is set. Microsoft VC++ thinks it's signed, so I see -1 if the bit is set. Ex. typedef enum {
1
1238
by: RoSsIaCrIiLoIA | last post by:
I have a union union r32{ uint8_t l; uint16_t x; uint32_t val; }; union r32 reg; and a function
12
2337
by: Merrill & Michele | last post by:
It's very difficult to do an exercise with elementary tools. It took me about fifteen minutes to get exercise 1-7: #include <stdio.h> int main(int orange, char **apple) { int c; c=-5; while(c != EOF ) {
5
2281
by: BillCo | last post by:
I'm having a problem with a union query, two simple queries joined with a union statement. It's created in code based on parameters. Users were noticing some inconsistant data and when I analysed the query produced and opened it from a MS Query it started giving strange results. The first query when run alone returns 22 records, some of which have identical values in all fields. This is 100% correct. The second query returns nothing....
6
2583
by: shaun roe | last post by:
For a bit of seasonal festive fun, I thought I'd try making a bitfield function, i.e. a function returning, for example, the value of bits 1 to 5 of a word as an integer, when the exact bits are known at compile time. The data word is always 32 bit unsigned integer (its a data stream from some embedded controller). The legacy code I have has lines like: errNum = (dataWord>>1) & 31; //bits 1 to 5 is an error code
0
10443
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
10216
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
10002
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
9044
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
7543
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
5437
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
5565
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3728
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2921
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.