How do bit operators work?

2

I have the following code:

volatile long Hex_To_int(long Hex , char bits)
{

  long Hex_2_int;
  char byte; 

  Hex_2_int = 0 ; 

  for(byte = 0 ; byte < bits ; byte++)
  {

     if(Hex& (0x0001 << byte)) Hex_2_int += 1*(pow(2,byte));

     else Hex_2_int  += 0*(pow(2,byte));

  }

  return Hex_2_int;
}

How does if work with bit operators in the following comparison?

if(Hex& (0x0001 << byte)) 
    
asked by anonymous 07.10.2015 / 00:49

2 answers

2

The code is strange and does unnecessary things.

The shift operation ( << operator) shifts the bits to the left. Since the position determines the number represented, as in the decimal, each bite shifted to the left multiplies by 2 (the base of the torque) the existing value. in this case each pass by the loop will produce 1, 2, 4, 8, etc.

The result will be computed with the variable Hex doing a and operation ( operador & ). The and works similarly to the multiplication, that is, each bit that one operand is calculated with the corresponding bite of the other operand. The result will be 1 whenever both are 1 and 0 when there is no such match.

The final result being a value other than zero executes if , since in C this is considered to be true. If the result is 0, it executes else .

Learn more here . The language is different but the operation is the same.

    
07.10.2015 / 01:34
0

I am a beginner in the technical (electronics) field and I have a lot of doubt as to the programming language c, someone can help with shift operators. I need to create a program with the following expressions:

a) Solve expression 16 2. Consider the result type to present the answer.

c) Solve the expression (4

09.04.2017 / 21:06