Help with bit shift in C ++

0

Well, in a programming exercise I was given the following program, and asked what is your output

 using namespace std; 

 union U1 {    
    union U2{     
      unsigned a: 3;   
      unsigned b: 4;   
      unsigned c: 1;    
    }u2;    
    int d;    
    void Exibe(unsigned, unsigned, unsigned, int); 
}u1; 

int main(){    
   u1.u2.a=2;    
   u1.u2.a<<=1;    
   u1.u2.b=16;     
   u1.u2.b-=4;    
   u1.u2.c=(u1.u2.b)>>3;    
   u1.d=17; 
   cout << u1.u2.a << "   " << u1.u2.b << "   " << u1.u2.c << "   " << u1.d << endl; 
} 

After the code execution the output is '1 1 1 17', my question is why this output, I researched bit shift and joining with the little that was given in class still can not understand, could help me to understand?

    
asked by anonymous 29.11.2016 / 01:50

1 answer

0

The bit shift moves the bits to the right or to the left and ends up meaning a multiplication or division by 2 of the value that was there, but it's a bit more complicated than that.

To help, let's follow your program line by line, showing the binary values:

int main(){    
   u1.u2.a=2;    
   u1.u2.a<<=1;    
   u1.u2.b=16;     
   u1.u2.b-=4;    
   u1.u2.c=(u1.u2.b)>>3;    
   u1.d=17; 
   cout << u1.u2.a << "   " << u1.u2.b << "   " << u1.u2.c << "   " << u1.d << endl; 
} 

1) The variable u1.u2.a in its case, starts with a value of 2 and has 3 bits.

a = 010

2) The variable is then shifted one bit to the left.

a = 100 (que é a mesma coisa que multiplicar por 2) e o valor vira 4

3) Variable b starts with 16 and has 4 bits. Which means that the value entered passes the value accepted by it ... So this is already beginning to reverse the understanding of what is happening (note that this is a bug and should not be done).

16 = 10000 
b = 0

4) Subtracting 4 from b, would leave the negative value, but it is unsigned, so you have another problem here, but the bits would be changed.

b = 1100

5) Then the bits of b are shifted to assign in c. 3 bits to the right.

b>>3 = 1
c = 1

6) Then by assigning 17 in d, everything that has been done is deleted.

17 = 10001

However, since U2 is a union, in doing so, you are also changing a, b and c:

a = 001 (três bits de 17)
b = 0001 (quatro bits de 17)
c = 1 (um bit de 17)
d = 17 (ele continua sendo um inteiro)
    
01.12.2016 / 14:23