Re: Trouble with bit fields
From: Victor Bazarov (v.Abazarov_at_comAcast.net)
Date: 08/18/04
- Next message: Ney André de Mello Zunino: "Re: Trouble with bit fields"
- Previous message: Ney André de Mello Zunino: "Trouble with bit fields"
- In reply to: Ney André de Mello Zunino: "Trouble with bit fields"
- Next in thread: Ney André de Mello Zunino: "Re: Trouble with bit fields"
- Reply: Ney André de Mello Zunino: "Re: Trouble with bit fields"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 18 Aug 2004 04:11:37 GMT
"Ney André de Mello Zunino" <zunino@inf.ufsc.br> wrote...
> 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
> {
> unsigned short opcode: 6;
> unsigned short rs: 5;
> unsigned short rt: 5;
> unsigned short immediate: 16;
> };
>
> int main()
> {
> instrucao_i i = { 0x24110064 };
> std::cout << std::hex;
> std::cout << "opcode: " << i.opcode << '\n';
> std::cout << " rs: " << i.rs << '\n';
> std::cout << " rt: " << i.rt << '\n';
> std::cout << "immed.: " << i.immediate << '\n';
> }
>
> Here is the binary representation of the 32-bit word being used to
> initialize /i/:
>
> 0010 0100 0001 0001 0000 0000 0110 0100
No. It's the 32-bit word you used to intialise i.opcode.
> Since the /opcode/ field is 6 bits long, it should be equal to the first
> 6 bits of /i/, i.e., 001001, which is 9 in decimal.
Why? The rules for initialising aggregates still apply. In order
to initialise a struct you need all elements mentioned.
> However, this is the
> output I get with both VC++ 7.1 and BCC32 5.5.1 on Windows:
>
> D:\Temp>teste
> opcode: 24
> rs: 0
> rt: 0
> immed.: 0
>
> Could anybody shed some light on this subject?
Initialisation of a struct is a very particular thing. Each initialiser
is used to initialise the respective member, and if there are fewer
initialisers than members, the remaining members are initialised to 0.
In your case you intialise 'opcode' with 0x24110064 (which cuts off its
last 6 bits, and yields 24), and the rest of them to zeroes. Why does
the result surprise you? If you wanted 9 in 'opcode', you should have
written
instrucao_i i = { 9, 0, 0x11, 0x64 };
Victor
- Next message: Ney André de Mello Zunino: "Re: Trouble with bit fields"
- Previous message: Ney André de Mello Zunino: "Trouble with bit fields"
- In reply to: Ney André de Mello Zunino: "Trouble with bit fields"
- Next in thread: Ney André de Mello Zunino: "Re: Trouble with bit fields"
- Reply: Ney André de Mello Zunino: "Re: Trouble with bit fields"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|