How do bit operators work?

Asked

Viewed 898 times

4

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 the if with operators of bit in that following comparison?

if(Hex& (0x0001 << byte)) 
  • The if works the same, no matter what has in it, you want to know how the operator of shift works? Be more specific.

  • I want to know the context of the operation. what are you doing

  • 1

    Notice that add up 0 (or 0 * qualquer coisa) is the same as not adding up: you can remove the else of the code :-)

  • You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? Something needs to be improved?

1 answer

2

The code is strange and does unnecessary things.

The operation of shift (operator <<) moves bits to the left. As the position determines the number represented, as in the decimal, each bit shifted to the left multiplies by 2 (the base of the binary) the existing value (as well as shifting a digit to the left in the decimal multiplies by 10, the base of the decimal). In this case each pass through the loop will produce 1, 2, 4, 8, etc.

The result will be calculated with the variable Hex doing an operation of and (operador &). The and works similarly to multiplication, i.e., 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 coincidence.

The final result being a non-zero value executes the if, since, in C, this is considered true. If the result is 0, executes the else.

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

  • 1

    Ya ... simplifying stays: unsigned long Hex_To_int(unsigned long Hex, char bits) { return Hex & ((1 << bits) - 1); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.