473,770 Members | 3,710 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to check bit fields order.

66 New Member
Hi everyone - I was reading in the K&R C book (on page 150) that (Bit) Fields are assigned left to right on some machines and right to left on others. This means listing the bit fields from most significant to least, or vice versa.

So I am creating a couple header files for drivers which contain structures of all the relevant bit fields....I need to "test" how my company's compiler orders the bit fields.

I was thinking about creating a file with one of the structures which lists the bit fields...and testing that. But how do I call it, and check that the first or last bit was read (I am also new to C) Please help! thanks!
Oct 13 '08 #1
14 11090
donbock
2,426 Recognized Expert Top Contributor
I need to "test" how my company's compiler orders the bit fields.
Why do you feel it is necessary to know precisely how bit fields are ordered by your compiler? If you're careful to write portable code then it won't matter to you how bit fields are ordered.

Exceptions I can think of:

1. You might be using bit fields to overlay a memory-mapped I/O register. Obviously, you can't be certain this strategy works unless you know how the compiler orders the bit fields. That's the precise reason why I advise you not to use bit fields in this way -- use bit masks instead.

2. You're writing a structure (that contains bit fields) to a file that might be read by another machine using a different compiler with different bit field ordering rules. You should define the format of portable data files carefully and completely without any reference to C/C++ keywords. Then write portable software that creates a data file conforming to that specifications.
Oct 13 '08 #2
dissectcode
66 New Member
In all possibility I could be mistaken when I think that the "compiler" orders the bit fields. Anyway - they need to be in an order, since they are mapping the hardware registers...ple ase help. thanks!
Oct 13 '08 #3
Banfa
9,065 Recognized Expert Moderator Expert
Determining the Order of Bit Fields

Method 1

RTFM! Your platform will undoubtedly have a platform guide (or user guide) and this is the sort of information it contains as well as such things as endianess, default sign of a char, processor bit size and other important stuff (if you happen to be writing non-portable code)

Method 2

Create a structure with bit fields in them, write 0 to them all, then write 1 to one of them. Put a break point on the following line of code and run the program in the platforms debugger.

Method 3

Don't bother, do what donblock said in 1 above use bit masks to access your hardware registers it is portable.
Oct 13 '08 #4
donbock
2,426 Recognized Expert Top Contributor
In all possibility I could be mistaken when I think that the "compiler" orders the bit fields. Anyway - they need to be in an order, since they are mapping the hardware registers...ple ase help. thanks!
I say again ... reconsider this approach. Suppose you do confirm that your compiler's bit field order matches the hardware registers. That doesn't mean that a newer version of the same compiler won't break your code by ordering the bit fields differently -- let alone what problems you may face if you change compiler vendor.

If you really do insist on this course of action then declare a union that overlays a char array with some bit fields. Repeatedly set the bit fields to different values and print the char array until you understand how your compiler organizes the bit fields. Then comment the operational bit field declaration like your life depends on it. Explain the bit field ordering that you expect; explain the hardware register layout that you're trying to match; explain how badly things will go wrong (not til run-time!) if a compiler upgrade changes the bit field ordering.

I insist on maximum portability. I don't let any of the sw engineers working for me use bit fields for memory-mapped I/O.
Oct 13 '08 #5
dissectcode
66 New Member
I say again ... reconsider this approach. Suppose you do confirm that your compiler's bit field order matches the hardware registers. That doesn't mean that a newer version of the same compiler won't break your code by ordering the bit fields differently -- let alone what problems you may face if you change compiler vendor.
Hello - I appreciate your feedback. What would be a better method, then, to "map" bit fields to registers? I would like to make sure I am doing the right thing for my company.
thanks!
Oct 13 '08 #6
drhowarddrfine
7,435 Recognized Expert Expert
Hm. Maybe I'm not thinking of something but the compiler doesn't arrange the bit fields but that the processor it runs on does. iow, bit 0-x are the same in all computers but the processor may fetch them 'big-endian'/'little-endian' but it doesn't matter to the compiler or software. In networking, endian matters and bits/bytes are swapped around on both ends sometimes.

Particularly if you are trying to interface directly with the processor in an embedded system, bit fields are set all the time.

But maybe I'm thinking like the hardware engineer that I am.
Oct 13 '08 #7
donbock
2,426 Recognized Expert Top Contributor
Nonportable aspects of bit fields (from the C89 Standard)

Undefined behavior:
1. A bit-field is declared with a type other than int, signed int, or unsigned int.

Implementation-defined behavior:
2. Whether a 'plain' int bit-field is treated as a signed int bit-field or as an unsigned int bit-field.
3. The order of allocation of bit-fields within a storage-unit.
4. The size of bit-field storage-units.
5. The maximum size of a bit field.
6. Whether a bit-field can straddle a storage-unit boundary. If a bit-field would cross a forbidden boundary, the compiler may issue a warning or it may silently move the bit-field to the next storage-unit.
7. An unnamed bit field of length 0 commands the compiler to pack no more bit fields in the current storage-unit. The storage-unit size is implementation dependent so the effect of this feature is also implementation dependent.

Kernighan & Ritchie (section 6.9) says
"Almost everything about [bit] fields is implementation-dependent."

One final problem: bit-fields will almost certainly not work properly on a write-only output register.
Oct 13 '08 #8
donbock
2,426 Recognized Expert Top Contributor
Hello - I appreciate your feedback. What would be a better method, then, to "map" bit fields to registers? I would like to make sure I am doing the right thing for my company.
thanks!
1. Not required, but I recommend you use specific-length typedefs for memory-mapped I/O words. That way you can simply redefine the typedef if a compiler upgrade changes the sizes of the built-in integer types.

2. Access the register through a pointer to the appropriate type. Use pointer-to-volatile. Assigning the address value to that pointer is inherently non-portable so don't worry about it.

3. For a register you intend to write to; determine if the software can read back the values that were written to it. If not, then you need to keep an image of the register in RAM. Don't forget to initialize the image and register. Notice that this creates a thread-safety risk: there is a timing window between when a new value goes into the image and when it goes into the register.

4. For read-only registers, declare the pointer as a pointer-to-volatile-const.

5. Use masking and shifting to set specific bits within a register; or extract specific bits from a register. It is easier if your fields are all unsigned. Here you're explicitly doing what the compiler hides from you if you use the bit-field feature. Avoid magic numbers -- use macros for the mask and shift values.

6. Perform the actual memory access through a function, one for reading and one for writing. Best if they are in their own file so the pointer-to-register is only useable by them, insuring that nobody breaks the rules by dereferencing the pointer themself. You can then include codec software as needed to handled endian conversions. This also limits the number of spots where you may need to single-thread to avoid race conditions.

For example:
Expand|Select|Wrap|Line Numbers
  1. typedef unsigned long HW_WORD;
  2. #define THEREGISTER_INIT_VALUE 0x000000FC
  3. static volatile HW_WORD * const theRegister = 0x8000400C;
  4. static HW_WORD theRegisterImage;
  5.  
  6. void writeRegister(HW_WORD value) {
  7.     theRegisterImage = value;
  8.     *theRegister = theRegisterImage;
  9. }
  10.  
  11. HW_WORD readRegister(void) {
  12.     return theRegisterImage;
  13. }
  14.  
  15. void initializeRegister(void) {
  16.    writeRegister(THEREGISTER_INIT_VALUE);
  17. }
  18.  
Oct 13 '08 #9
Banfa
9,065 Recognized Expert Moderator Expert
Hm. Maybe I'm not thinking of something but the compiler doesn't arrange the bit fields but that the processor it runs on does.
Not quite right.

The compiler doesn't arrange the bit order in a byte but that the processor it runs on does.

That is not the same as a bit field in a defined structure. When you declare a bit field the compiler reserves some space (at least 1 byte but it can be more depending on the compiler/platform). Then within that allocated byte(s) the compiler chooses which bit it will use to represent the bit field you declared. It has free reign to allocate any bit (from 3 in dons post).

Bit order in the byte is hardware dependent but bit field order in the data allocated to hold that bit field is compiler dependent.
Oct 14 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
1989
by: J P Singh | last post by:
Hi All I have been given the task to create a search page to search on of the tables in the sql database. I have been asked that the user should be able to search any field(which I have done) but he should also be able to customise the form to display or hide any feilds in the results. My table has about 20 feilds and different users wanting to you the search
9
2113
by: Paul Morrow | last post by:
I have seen the technique where a number of rows in a database are displayed in an html table so that each column of each row is editable. They use a single form surrounding the table, where each field in any given column has the same control name. So for example, in the last_name column, every row in the table would contain an input field (of type "text") with the name "last_name". Is this safe to do? I know that multiple radio...
5
6320
by: Steve Wylie | last post by:
I am constructing an HTML questionnaire and one of the questions requires people to rate some choices from 1 to 5, where 1 is their favourite and 5 is their least favourite: Car Bus Taxi cab Train Airplane
5
24638
by: Krechting | last post by:
Hi ALl, I have a code that checks if the documents in a hyperlink field are still where they should be. I use fileexist(). First I want to filter out all the hyperlink fields that are empty. I open a recordset and browse through all the fields to check for the word file. I cannot filter out the empty fields. I have tried: If Len(.Fields("Link") <> 0 then and: If Not IsNull(.Fields("Link")) then
10
3054
by: Abhi | last post by:
In ANSI C, we can have a bit fields inside structure like struct _A { int i:2; }; would define a variable of 2-bit length. My doubt is that what would the size of this structure then? Would it be sizeof(int) or just 1 byte? I know that it is quite compiler specific, but what it should be according to the ANSI standard? I couldn't find exact documentation
6
8371
by: fstenoughsnoopy | last post by:
I have a customer order database and I need to pull a customers information, ie first name, last name, address, city, state, zip, phone, etc, into the oder table. i don't know how to go about making this work...
3
1877
by: fstenoughsnoopy | last post by:
Ok the complete story. I have a Contact Table, Query and Form, that are used to input and store the contact info for customers. They have FirstName, LastName and Address as the primary key fields to keep out duplicates. I am trying to put a full name box on the query, that uses the FirstName, LastName and Middle Initial and puts them together to form a full name. That I have so far. On my order database(consisting of a master table with...
11
6662
imrosie
by: imrosie | last post by:
Hello Experts This is a hard one (I still speak newbie). An expert may think it's not a big deal, but, I am trying to replace my Main Order form with a subform because of the following: Original form was based on a query of 2 tables (Order and Customers), the subform was based on table OrderDetail(productname, quantity, discount, unitprice). I was experiencing autonumber problems when attempting to start a new order, because of the inner...
82
10068
by: happyse27 | last post by:
Hi All, I modified the user registration script, but not sure how to make it check for each variable in terms of preventing junk registration and invalid characters? Two codes below : a) html b) perl script (print and inserting into database) Cheers... Andrew
0
9595
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
9432
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,...
1
10008
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
9873
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...
1
7420
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
6682
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
5313
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...
1
3974
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
3578
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.