toBytes method

Uint8List toBytes()

Encodes the command per ISO 7816-4.

Implementation

Uint8List toBytes() {
  final out = BytesBuilder(copy: false);
  out.add([instructionClass, instructionCode, p1Parameter, p2Parameter]);

  final body = data;
  final le = expectedResponseLength;
  if (body == null && le == null) return out.takeBytes(); // Case 1: the header is the whole command.

  if (!isExtended) {
    if (body != null) {
      out.addByte(body.length); // Case 3S and 4S.
      out.add(body);
    }
    if (le != null) out.addByte(le == 256 ? 0x00 : le); // Case 2S and 4S; 256 is spelled 0x00.
    return out.takeBytes();
  }

  // The `0x00` marker announces the extended fields, and it is written exactly once. A
  // command that carries data spends it on Lc, so its Le follows the data field as a bare
  // pair of bytes; a command with no data spends it on Le instead.
  out.addByte(0x00);
  if (body != null) {
    out.add([(body.length >> 8) & 0xFF, body.length & 0xFF]); // Case 3E and 4E.
    out.add(body);
  }
  if (le != null) out.add([(le >> 8) & 0xFF, le & 0xFF]); // Case 2E and 4E; 65536 wraps to 0x0000.

  return out.takeBytes();
}