Simvik

Make a driver function MISRA compliant

Working code that the project's MISRA checker rejects: fix every finding without changing what it does. An easy embedded C problem (Static analysis and MISRA…

easy · Static analysis and MISRA in practice · misra · static-analysis · coding-standards · essential-types

status_bits works, and its tests would pass, but this is a safety project: the build runs a MISRA C checker, and any finding fails it. The checker is part of this problem, and the rules it enforces are listed below.

status_bits(flags, mode) builds a status byte: bit 4 if flags bit 0 is set, bit 5 if flags bit 7 is set, and then bit 0 for mode 0, or bit 1 for modes 1 and 2. Other modes add nothing.

Press Run to see the findings. Then change the code until there are none, and the tests still pass.

Starter code

uint8_t status_bits(uint8_t flags, int32_t mode) {
  uint8_t out = 0;
  if (flags & 0x01) out |= 0x10;
  if (flags & 0x80) out |= 0x20;
  switch (mode) {
    case 0: out |= 1; break;
    case 1:
    case 2: out |= 2; break;
  }
  return out;
}

Example tests

Each flag and mode

show(0x00, 0);
show(0x01, 1);
show(0x80, 2);
show(0x81, 5);

Expected output:

flags 0x00, mode 0: 0x01
flags 0x01, mode 1: 0x12
flags 0x80, mode 2: 0x22
flags 0x81, mode 5: 0x30

Learn it first

More Static analysis and MISRA in practice problems