setBit static method

void setBit(
  1. Uint8List bytes,
  2. int bitIndex,
  3. bool value
)

Set specific bit in byte array.

Parameters:

  • bytes: Byte array
  • bitIndex: Bit index (0-based)
  • value: true to set bit, false to clear bit

Example:

final coils = Uint8List(2);
DataConverter.setBit(coils, 5, true);
await client.writeMultipleCoils(1, 0, 16, coils);

Implementation

static void setBit(Uint8List bytes, int bitIndex, bool value) {
  final byteIndex = bitIndex ~/ 8;
  final bitOffset = bitIndex % 8;
  if (byteIndex >= bytes.length) {
    throw RangeError('Bit index $bitIndex out of range');
  }
  if (value) {
    bytes[byteIndex] |= (1 << bitOffset);
  } else {
    bytes[byteIndex] &= ~(1 << bitOffset);
  }
}