Z
Z
zompin2016-04-11 14:10:14
C++ / C#
zompin, 2016-04-11 14:10:14

Why does this code work differently?

unsigned short crc16(unsigned char ch) {
  unsigned short crc = 0xffff;
  unsigned short poly = 0x1021;
  char i;
  crc ^= ch << 8;
  for (i = 0; i < 8; i++) {
    if (crc & 0x8000) {
      crc <<= 1;
      crc ^= 0x1021;
    } else {
      crc <<= 1;
    }
  }
  return crc;
}

unsigned short crc16(unsigned char ch) {
  unsigned short crc = 0xffff;
  unsigned short poly = 0x1021;
  char i;
  crc ^= ch << 8;
  for (i = 0; i < 8; i++) {
    crc <<= 1;
    if (crc & 0x8000) {
      crc ^= 0x1021;
    }
  }
  return crc;
}

Two code options. In the first case, the bit shift is performed in the if block (in both cases), in the second, before. Why does this code work differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
iv_k, 2016-04-11
@iv_k

weird question. this should work differently. in the first case you have a condition before the shift, in the second case after the shift.

Z
zompin, 2016-04-11
@zompin

Got it. In the first case, there is just a comparison, in the second case, a comparison of the result of the shift.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question