Serial.print variable not printing right

Simple flipping a byte from LSB to MSB
it all works from 0 to 253 except the number 254
254 prints 255 binary
any ideas ?


// flipping a byte from LSB to MSB.

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  int var;     
  int i, x, y, p;
  int s = 8;    // number of bits in 'num'. (This case a 8bit byte)
  int num = 254 ; // number to flip

  for (i = 0; i < (s / 2); i++) {
    // extract bit on the left, from MSB
    p = s - i - 1;
    x = num & (1 << p);
    x = x >> p;  
    // extract bit on the right, from LSB
    y = num & (1 << i);
    y = y >> i;
  
    var = var | (x << i);       // apply x
    var = var | (y << p);       // apply y
  }
  Serial.println(var);       // working
  Serial.println(var, BIN); // not working
  delay(500);
}

Thanks

Why do you think it's not working? 127 is the same as 1111111B.
It prints seven '1' - leading zero's are not printed!

But you should initialize 'var' to zero as @Delta_G already pointed out. Otherwise it is a coincidence if it is 0.

Me Bad...
i need new glasses
and
int var = 0
Thank You