[RESOLVED] Question about unions,bitfields
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Thread: [RESOLVED] Question about unions,bitfields

Threaded View

  1. #1
    Join Date
    Oct 2009
    Posts
    40

    [RESOLVED] Question about unions,bitfields

    Code:
     #include <iostream>
    
    using namespace std;
    
    struct dore
    {
    
    
       unsigned b1:1;
       unsigned b2:1;
       unsigned b3:1;
       unsigned b4:1;
       unsigned b5:1;
       unsigned b6:1;
       unsigned b7:1;
       unsigned b8:1;
       unsigned b9:1;
       unsigned b10:1;
       unsigned b11:1;
       unsigned b12:1;
       unsigned b13:1;
       unsigned b14:1;
       unsigned b15:1;
       unsigned b16:1;
       unsigned b17:1;
       unsigned b18:1;
       unsigned b19:1;
       unsigned b20:1;
       unsigned b21:1;
       unsigned b22:1;
       unsigned b23:1;
       unsigned b24:1;
       unsigned b24:1;
       unsigned b25:1;
       unsigned:b26:1;
       unsigned b27:1;
       unsigned b28:1;
       unsigned b29:1;
       unsigned b30:1;
       unsigned b31:1;
       unsigned b32:1;
    };
    
    
    union s
    {
       int num;
       struct dore ya2;
      
    };
    
    
    int main()
    {
        int sayi;
        s yapi1;
       
        cout << "Enter a number";
        cin >> sayi;
        yapi1.num=sayi;
        
        cout << yapi1.num << endl;
        cout << sizeof(yapi1.num);
    
         if (yapi1.ya2.b1==1) cout << "1";
         else cout << "0";
         if (yapi1.ya2.b2==1) cout << "1";
         else cout << "0";
       
    
          if (yapi1.ya2.b3==1) cout << "1";
         else cout << "0";
         if (yapi1.ya2.b4==1) cout << "1";
         else cout << "0";
    
         if (yapi1.ya2.b5==1) cout << "1";
         else cout <<"0";
         if (yapi1.ya2.b6==1) cout << "1";
         else cout <<"0";
    
         if (yapi1.ya2.b7==1) cout << "1";
         else cout <<"0";
         if (yapi1.ya2.b8==1) cout << "1";
         else cout <<"0";
    
    
    }
    This code works,it prints the first 8 bits of the given number.

    But if I change this code:
    Code:
     unsigned b1:1;
    unsigned b2:1;
    unsigned b3:1;
    unsigned b4:1;
    unsigned b5:1;
    unsigned b6:1;
    unsigned b7:1;
    unsigned b8:1;
    unsigned b9:1;
    unsigned b10:1;
    ...
    };
    to :
    Code:
    int b1:1;
    int b2:1;
    int b3:1; 
    ...
    then it doesn't work right.Why does using unsigned work although using int doesn't work as I expected?
    Last edited by AwArEnEsS; April 23rd, 2013 at 12:03 AM. Reason: I reformatted code snippets

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center