stringToBytes static method

Uint8List stringToBytes(
  1. String value, {
  2. int? length,
})

Convert string to bytes.

Parameters:

  • value: String to convert
  • length: Fixed length (pads with nulls if needed)

Returns: Byte array with ASCII characters

Example:

final deviceName = 'PLC-001';
final bytes = DataConverter.stringToBytes(deviceName, length: 20);
await client.writeMultipleRegistersBytes(1, 300, 10, bytes);

Implementation

static Uint8List stringToBytes(String value, {int? length}) {
  final codeUnits = value.codeUnits;
  if (length == null) {
    return Uint8List.fromList(codeUnits);
  }
  final result = Uint8List(length);
  final copyLength = codeUnits.length > length ? length : codeUnits.length;
  result.setRange(0, copyLength, codeUnits);
  return result;
}