Simvik

Pack a signal into a frame

Place a little-endian signal of any length at any bit, without disturbing the others. A medium embedded C problem (CAN), run and graded in the browser.

medium · CAN · can · bits · dbc

CAN signals are described in DBC files by a start bit and a length. For little-endian ("Intel") signals, the signal's least significant bit goes at the start bit, and the following bits go upwards: bit k of the payload is bit k % 8 of byte k / 8. A signal may cross byte boundaries.

Write put_signal(data, start, length, raw), which stores the low length bits of raw (1 to 32) without changing any other bit of the 8-byte payload, and get_signal(data, start, length), which reads it back.

Starter code

void put_signal(uint8_t data[8], int start, int length, uint32_t raw) {
  (void)length;
  data[start / 8] |= (uint8_t)(raw << (start % 8));
}

uint32_t get_signal(const uint8_t data[8], int start, int length) {
  return (data[start / 8] >> (start % 8)) & ((1u << length) - 1);
}

Example tests

A 16-bit engine speed at bit 8

uint8_t d[8] = {0};
put_signal(d, 8, 16, 3000);
dump(d);
printf("%u\n", get_signal(d, 8, 16));

Expected output:

00 B8 0B 00 00 00 00 00
3000

Neighbours are untouched

uint8_t d[8] = { 0xFF, 0xFF, 0, 0, 0, 0, 0, 0 };
put_signal(d, 4, 4, 0x5);
dump(d);

Expected output:

5F FF 00 00 00 00 00 00

Learn it first

  • CAN · Arbitration, bit timing, frames, CAN FD and error handling.

More CAN problems